By AngryHacker


2011-07-14 01:15:29 8 Comments

I'll be copying a large file over the network using my winforms app and I need to show some kind of progress bar. Rather than cook up my own copy routine, I was thinking that it might be better to simply show the built-in file copy dialog.

I would also need a "Copy complete" and "Copy failed" notification.

I need this to work on Windows XP, Vista and 7. Is there a way to call to engage this functionality from my c# code?

2 comments

@ssz 2018-10-16 05:08:22

I know it's a old thread but I faced to similar requirement and finally this is the code I used, maybe it helps someone else. the credit belongs to here

using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Pietschsoft
{
    public class NativeProgressDialog
    {
        private IntPtr parentHandle;

        private Win32IProgressDialog pd = null;

        private string title = string.Empty;
        private string cancelMessage = string.Empty;
        private string line1 = string.Empty;
        private string line2 = string.Empty;
        private string line3 = string.Empty;
        private uint value = 0;
        private uint maximum = 100;

        public string Title
        {
            get
            {
                return this.title;
            }
            set
            {
                this.title = value;
                if (pd != null)
                {
                    pd.SetTitle(this.title);
                }
            }
        }

        public string CancelMessage
        {
            get
            {
                return this.cancelMessage;
            }
            set
            {
                this.cancelMessage = value;
                if (pd != null)
                {
                    pd.SetCancelMsg(this.cancelMessage, null);
                }
            }
        }

        public string Line1
        {
            get
            {
                return this.line1;
            }
            set
            {
                this.line1 = value;
                if (pd != null)
                {
                    pd.SetLine(1, this.line1, false, IntPtr.Zero);
                }
            }
        }

        public string Line2
        {
            get
            {
                return this.line2;
            }
            set
            {
                this.line2 = value;
                if (pd != null)
                {
                    pd.SetLine(2, this.line2, false, IntPtr.Zero);
                }
            }
        }

        public string Line3
        {
            get
            {
                return this.line3;
            }
            set
            {
                this.line3 = value;
                if (pd != null)
                {
                    pd.SetLine(3, this.line3, false, IntPtr.Zero);
                }
            }
        }

        public uint Value
        {
            get
            {
                return this.value;
            }
            set
            {
                this.value = value;
                if (pd != null)
                {
                    pd.SetProgress(this.value, this.maximum);
                }
            }
        }

        public uint Maximum
        {
            get
            {
                return this.maximum;
            }
            set
            {
                this.maximum = value;
                if (pd != null)
                {
                    pd.SetProgress(this.value, this.maximum);
                }
            }
        }
        public bool HasUserCancelled
        {
            get
            {
                if (pd != null)
                {
                    return pd.HasUserCancelled();
                }
                else
                    return false;
            }
        }

        public NativeProgressDialog(IntPtr parentHandle)
        {
            this.parentHandle = parentHandle;
        }

        public void ShowDialog(params PROGDLG[] flags)
        {
            if (pd == null)
            {
                pd = (Win32IProgressDialog)new Win32ProgressDialog();

                pd.SetTitle(this.title);
                pd.SetCancelMsg(this.cancelMessage, null);
                pd.SetLine(1, this.line1, false, IntPtr.Zero);
                pd.SetLine(2, this.line2, false, IntPtr.Zero);
                pd.SetLine(3, this.line3, false, IntPtr.Zero);

                PROGDLG dialogFlags = PROGDLG.Normal;
                if (flags.Length != 0)
                {
                    dialogFlags = flags[0];
                    for (var i = 1; i < flags.Length; i++)
                    {
                        dialogFlags = dialogFlags | flags[i];
                    }
                }

                pd.StartProgressDialog(this.parentHandle, null, dialogFlags, IntPtr.Zero);
            }
        }

        public void CloseDialog()
        {
            if (pd != null)
            {
                pd.StopProgressDialog();
                //Marshal.ReleaseComObject(pd);
                pd = null;
            }
        }


        #region "Win32 Stuff"
        // The below was copied from: http://pinvoke.net/default.aspx/Interfaces/IProgressDialog.html

        public static class shlwapi
        {
            [DllImport("shlwapi.dll", CharSet = CharSet.Auto)]
            static extern bool PathCompactPath(IntPtr hDC, [In, Out] StringBuilder pszPath, int dx);
        }

        [ComImport]
        [Guid("EBBC7C04-315E-11d2-B62F-006097DF5BD4")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public interface Win32IProgressDialog
        {
            /// <summary>
            /// Starts the progress dialog box.
            /// </summary>
            /// <param name="hwndParent">A handle to the dialog box's parent window.</param>
            /// <param name="punkEnableModless">Reserved. Set to null.</param>
            /// <param name="dwFlags">Flags that control the operation of the progress dialog box. </param>
            /// <param name="pvResevered">Reserved. Set to IntPtr.Zero</param>
            void StartProgressDialog(
                IntPtr hwndParent, //HWND
                [MarshalAs(UnmanagedType.IUnknown)]    object punkEnableModless, //IUnknown
                PROGDLG dwFlags,  //DWORD
                IntPtr pvResevered //LPCVOID
                );

            /// <summary>
            /// Stops the progress dialog box and removes it from the screen.
            /// </summary>
            void StopProgressDialog();

            /// <summary>
            /// Sets the title of the progress dialog box.
            /// </summary>
            /// <param name="pwzTitle">A pointer to a null-terminated Unicode string that contains the dialog box title.</param>
            void SetTitle(
                [MarshalAs(UnmanagedType.LPWStr)] string pwzTitle //LPCWSTR
                );

            /// <summary>
            /// Specifies an Audio-Video Interleaved (AVI) clip that runs in the dialog box. Note: Note  This method is not supported in Windows Vista or later versions.
            /// </summary>
            /// <param name="hInstAnimation">An instance handle to the module from which the AVI resource should be loaded.</param>
            /// <param name="idAnimation">An AVI resource identifier. To create this value, use the MAKEINTRESOURCE macro. The control loads the AVI resource from the module specified by hInstAnimation.</param>
            void SetAnimation(
                IntPtr hInstAnimation, //HINSTANCE
                ushort idAnimation //UINT
                );

            /// <summary>
            /// Checks whether the user has canceled the operation.
            /// </summary>
            /// <returns>TRUE if the user has cancelled the operation; otherwise, FALSE.</returns>
            /// <remarks>
            /// The system does not send a message to the application when the user clicks the Cancel button.
            /// You must periodically use this function to poll the progress dialog box object to determine
            /// whether the operation has been canceled.
            /// </remarks>
            [PreserveSig]
            [return: MarshalAs(UnmanagedType.Bool)]
            bool HasUserCancelled();

            /// <summary>
            /// Updates the progress dialog box with the current state of the operation.
            /// </summary>
            /// <param name="dwCompleted">An application-defined value that indicates what proportion of the operation has been completed at the time the method was called.</param>
            /// <param name="dwTotal">An application-defined value that specifies what value dwCompleted will have when the operation is complete.</param>
            void SetProgress(
                uint dwCompleted, //DWORD
                uint dwTotal //DWORD
                );

            /// <summary>
            /// Updates the progress dialog box with the current state of the operation.
            /// </summary>
            /// <param name="ullCompleted">An application-defined value that indicates what proportion of the operation has been completed at the time the method was called.</param>
            /// <param name="ullTotal">An application-defined value that specifies what value ullCompleted will have when the operation is complete.</param>
            void SetProgress64(
                ulong ullCompleted, //ULONGLONG
                ulong ullTotal //ULONGLONG
                );

            /// <summary>
            /// Displays a message in the progress dialog.
            /// </summary>
            /// <param name="dwLineNum">The line number on which the text is to be displayed. Currently there are three lines—1, 2, and 3. If the PROGDLG_AUTOTIME flag was included in the dwFlags parameter when IProgressDialog::StartProgressDialog was called, only lines 1 and 2 can be used. The estimated time will be displayed on line 3.</param>
            /// <param name="pwzString">A null-terminated Unicode string that contains the text.</param>
            /// <param name="fCompactPath">TRUE to have path strings compacted if they are too large to fit on a line. The paths are compacted with PathCompactPath.</param>
            /// <param name="pvResevered"> Reserved. Set to IntPtr.Zero.</param>
            /// <remarks>This function is typically used to display a message such as "Item XXX is now being processed." typically, messages are displayed on lines 1 and 2, with line 3 reserved for the estimated time.</remarks>
            void SetLine(
                uint dwLineNum, //DWORD
                [MarshalAs(UnmanagedType.LPWStr)] string pwzString, //LPCWSTR
                [MarshalAs(UnmanagedType.VariantBool)] bool fCompactPath, //BOOL
                IntPtr pvResevered //LPCVOID
                );

            /// <summary>
            /// Sets a message to be displayed if the user cancels the operation.
            /// </summary>
            /// <param name="pwzCancelMsg">A pointer to a null-terminated Unicode string that contains the message to be displayed.</param>
            /// <param name="pvResevered">Reserved. Set to NULL.</param>
            /// <remarks>Even though the user clicks Cancel, the application cannot immediately call
            /// IProgressDialog::StopProgressDialog to close the dialog box. The application must wait until the
            /// next time it calls IProgressDialog::HasUserCancelled to discover that the user has canceled the
            /// operation. Since this delay might be significant, the progress dialog box provides the user with
            /// immediate feedback by clearing text lines 1 and 2 and displaying the cancel message on line 3.
            /// The message is intended to let the user know that the delay is normal and that the progress dialog
            /// box will be closed shortly.
            /// It is typically is set to something like "Please wait while ...". </remarks>
            void SetCancelMsg(
                [MarshalAs(UnmanagedType.LPWStr)] string pwzCancelMsg, //LPCWSTR
                object pvResevered //LPCVOID
                );

            /// <summary>
            /// Resets the progress dialog box timer to zero.
            /// </summary>
            /// <param name="dwTimerAction">Flags that indicate the action to be taken by the timer.</param>
            /// <param name="pvResevered">Reserved. Set to NULL.</param>
            /// <remarks>
            /// The timer is used to estimate the remaining time. It is started when your application
            /// calls IProgressDialog::StartProgressDialog. Unless your application will start immediately,
            /// it should call Timer just before starting the operation.
            /// This practice ensures that the time estimates will be as accurate as possible. This method
            /// should not be called after the first call to IProgressDialog::SetProgress.</remarks>
            void Timer(
                PDTIMER dwTimerAction, //DWORD
                object pvResevered //LPCVOID
                );

        }

        [ComImport]
        [Guid("F8383852-FCD3-11d1-A6B9-006097DF5BD4")]
        public class Win32ProgressDialog
        {
        }

        /// <summary>
        /// Flags that indicate the action to be taken by the ProgressDialog.SetTime() method.
        /// </summary>
        public enum PDTIMER : uint //DWORD
        {
            /// <summary>Resets the timer to zero. Progress will be calculated from the time this method is called.</summary>
            Reset = (0x01),
            /// <summary>Progress has been suspended.</summary>
            Pause = (0x02),
            /// <summary>Progress has been resumed.</summary>
            Resume = (0x03)
        }

        [Flags]
        public enum PROGDLG : uint //DWORD
        {
            /// <summary>Normal progress dialog box behavior.</summary>
            Normal = 0x00000000,
            /// <summary>The progress dialog box will be modal to the window specified by hwndParent. By default, a progress dialog box is modeless.</summary>
            Modal = 0x00000001,
            /// <summary>Automatically estimate the remaining time and display the estimate on line 3. </summary>
            /// <remarks>If this flag is set, IProgressDialog::SetLine can be used only to display text on lines 1 and 2.</remarks>
            AutoTime = 0x00000002,
            /// <summary>Do not show the "time remaining" text.</summary>
            NoTime = 0x00000004,
            /// <summary>Do not display a minimize button on the dialog box's caption bar.</summary>
            NoMinimize = 0x00000008,
            /// <summary>Do not display a progress bar.</summary>
            /// <remarks>Typically, an application can quantitatively determine how much of the operation remains and periodically pass that value to IProgressDialog::SetProgress. The progress dialog box uses this information to update its progress bar. This flag is typically set when the calling application must wait for an operation to finish, but does not have any quantitative information it can use to update the dialog box.</remarks>
            NoProgressBar = 0x00000010
        }
        #endregion
    }
}

How you can use it:

private Pietschsoft.NativeProgressDialog pd;
private uint progressPercent;

Timer timer1 = new Timer();
private void button1_Click_1(object sender, EventArgs e)
{
    timer1.Interval = 300;
    timer1.Tick += (s,ev)=>
    {
        progressPercent++;

        if (pd.HasUserCancelled)
        {
            timer1.Stop();
            pd.CloseDialog();
        }
        else
        {
            // Update the progress value
            pd.Value = progressPercent;

            pd.Line2 = "Percent " + progressPercent.ToString() + "%";

            if (progressPercent >= 100)
            {
                timer1.Stop();
                pd.CloseDialog();
            }
        }
    };


    pd = new Pietschsoft.NativeProgressDialog(this.Handle);
    pd.Title = "Performing Operation";
    pd.CancelMessage = "Please wait while the operation is cancelled";
    pd.Maximum = 100;
    pd.Value = 0;
    pd.Line1 = "Line One";
    pd.Line3 = "Calculating Time Remaining...";

    //pd.ShowDialog(); // Defaults to PROGDLG.Normal
    pd.ShowDialog(Pietschsoft.NativeProgressDialog.PROGDLG.Modal, Pietschsoft.NativeProgressDialog.PROGDLG.AutoTime, Pietschsoft.NativeProgressDialog.PROGDLG.NoMinimize);

    progressPercent = 0;
    timer1.Start();
}

@ja72 2011-07-14 01:24:14

Answer taken from: here

Windows Vista does indeed include a new copy engine that supports exactly what you're looking to do. However, it's possible that previously existing functionality may meet your needs. For example, if you want to copy, move, rename, or delete an individual file or directory, you can take advantage of SHFileOperation (exposed from shell32.dll), which is already wrapped by the Visual Basic® runtime. If you're using Visual Basic 2005, you can simply use functionality from the My namespace, for example:

 My.Computer.FileSystem.CopyDirectory(
   sourcePath, destinationPath, UIOption.AllDialogs)

Accomplishing the same thing in C# involves only a little more work, adding a reference to Microsoft.VisualBasic.dll (from the Microsoft® .NET Framework installation directory) and using code such as the following:

using Microsoft.VisualBasic.FileIO;
...
FileSystem.CopyDirectory(
    sourcePath, destinationPath, UIOption.AllDialogs);

When run, this will result in the same progress UI you'd see if you were doing the same file operations from Windows Explorer. In fact, when running on Windows Vista, you automatically get the new Window Vista progress UI, as shown in Figure 1. Dialog

@Tim Post 2011-07-21 07:19:59

When citing a source, cite the source in block quotes. Answers that just cite something else without any additional context or explanation are generally frowned upon.

@ja72 2014-05-04 20:49:09

Mostly it is quoted, but not verbatim. Some edits for brevity where made and so I decided not to blockquote. I edited the post recently it is going to make the community happier.

@Frank R. 2016-06-30 22:59:05

I need to write a backup and restore util that displays the GUI progress dialog box you provided in your answer, but prefer a compiled exe that doesn't require a runtime or framework. Can this be accomplished with win32 c++ (visual-c++)?.. If true, problem is I don't know how to write it in visual-c++

@ja72 2016-07-02 22:32:03

Seems like you need to post a new question in hopes someone can help you.

@LuckyLuke82 2017-01-16 20:24:27

@ja72, do you maybe know how to determine which button was clicked in case of file conflict dialog box (skip, cancel, copy&replace, copy& rename buttons etc.)? Just catch exceptions for each button?...I need this for doing changes in my Listview Explorer.

@ja72 2017-01-16 21:25:35

A cancel button will fire an exception. See msdn.microsoft.com/en-us/library/ms128119(v=vs.110).aspx

@KnorxThieus 2017-08-11 18:38:00

Does anyone have an idea how I can call this dialog for multiple copy/move tasks at once? Showing 1,001 separate dialog windows seems not very user-friendly to me.

@ja72 2017-08-11 18:59:17

@KnorxThieus I think win7 and above will automatically combine the dialog boxes. At least it does when manually doing various long copy operations.

@KnorxThieus 2017-08-17 15:52:07

@ja72 Yes and no. Win8 and above will, provided that you invoke the MoveFile/CopyFile method asynchronously for each task, bundle all tasks to one scrollable window, but I do not manage to get a display like the screenshot above shows with "Copying/Moving n files" processing all tasks one after the other instead of at once.

Related Questions

Sponsored Content

27 Answered Questions

[SOLVED] How to cast int to enum?

  • 2008-08-27 03:58:21
  • lomaxx
  • 1306210 View
  • 3074 Score
  • 27 Answer
  • Tags:   c# enums casting int

32 Answered Questions

[SOLVED] How do I generate a random int number?

  • 2010-04-24 23:09:11
  • Rella
  • 2202213 View
  • 1835 Score
  • 32 Answer
  • Tags:   c# random

17 Answered Questions

[SOLVED] Copying files from Docker container to host

29 Answered Questions

[SOLVED] How to enumerate an enum

16 Answered Questions

[SOLVED] How do I copy a file in Python?

44 Answered Questions

[SOLVED] How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?

  • 2008-09-29 22:30:28
  • mistrmark
  • 1060622 View
  • 1829 Score
  • 44 Answer
  • Tags:   c# .net excel file-io

39 Answered Questions

17 Answered Questions

12 Answered Questions

[SOLVED] How to create a dialog with “yes” and “no” options?

  • 2012-02-17 20:03:21
  • crchin
  • 842298 View
  • 642 Score
  • 12 Answer
  • Tags:   javascript dialog

1 Answered Questions

[SOLVED] Display Windows File Copy Dialog when copying from a Memorystream?

Sponsored Content