C#: Using IProgressDialog to show a “native” Progress Dialog from .NET in Windows

A few months ago I posted some code that I originally wrote back in about 2004. Well, I was looking through some more of my prototypes that I’ve written and I came across the following example of how to use the IProgressDialog Win32 Interface to harness the power of the Built-in Progress Dialog in Windows within your own .NET applications.

I have test this on WIndows 7, but it should work as expected on Windows XP and Vista. The MSDN Documentation for IProgressDialog says it’s minimum supported operating systems are Windows 2000 and Windows XP.

The full source code for this example is listed below. Just copy from this post and paste it within your app to test.

ProgressDialog Usage Example

Here’s an example of how to use this example “ProgressDialog” class: This is an example of using it from Windows Forms, however it could be used from within WPF exactly the same way.

using System;
using System.Windows.Forms;

namespace WindowsProgressDialog
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Pietschsoft.ProgressDialog pd;
        private uint progressPercent;

        private void button1_Click(object sender, EventArgs e)
        {
            pd = new Pietschsoft.ProgressDialog(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.ProgressDialog.PROGDLG.Modal, Pietschsoft.ProgressDialog.PROGDLG.AutoTime, Pietschsoft.ProgressDialog.PROGDLG.NoMinimize);

            progressPercent = 0;
            timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            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();
                }
            }
        }
    }
}

ProgressDialog Class

And, here’s the full code for the ProgressDialog class itself:

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

namespace Pietschsoft
{
    public class ProgressDialog
    {
        private IntPtr _parentHandle;

        private Win32IProgressDialog pd = null;

        public ProgressDialog(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;
            }
        }

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

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

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

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

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

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

        private uint _maximum = 100;
        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;
            }
        }

        #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
        {
            /// 

            /// Starts the progress dialog box.
            /// 

            /// A handle to the dialog box's parent window.
            /// Reserved. Set to null.
            /// Flags that control the operation of the progress dialog box. 
            /// Reserved. Set to IntPtr.Zero
            void StartProgressDialog(
                IntPtr hwndParent, //HWND
                [MarshalAs(UnmanagedType.IUnknown)]    object punkEnableModless, //IUnknown
                PROGDLG dwFlags,  //DWORD
                IntPtr pvResevered //LPCVOID
                );

            /// 

            /// Stops the progress dialog box and removes it from the screen.
            /// 

            void StopProgressDialog();

            /// 

            /// Sets the title of the progress dialog box.
            /// 

            /// A pointer to a null-terminated Unicode string that contains the dialog box title.
            void SetTitle(
                [MarshalAs(UnmanagedType.LPWStr)] string pwzTitle //LPCWSTR
                );

            /// 

            /// 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.
            /// 

            /// An instance handle to the module from which the AVI resource should be loaded.
            /// An AVI resource identifier. To create this value, use the MAKEINTRESOURCE macro. The control loads the AVI resource from the module specified by hInstAnimation.
            void SetAnimation(
                IntPtr hInstAnimation, //HINSTANCE
                ushort idAnimation //UINT
                );

            /// 

            /// Checks whether the user has canceled the operation.
            /// 

            /// TRUE if the user has cancelled the operation; otherwise, FALSE.
            /// 
            /// 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.
            /// 
            [PreserveSig]
            [return: MarshalAs(UnmanagedType.Bool)]
            bool HasUserCancelled();

            /// 

            /// Updates the progress dialog box with the current state of the operation.
            /// 

            /// An application-defined value that indicates what proportion of the operation has been completed at the time the method was called.
            /// An application-defined value that specifies what value dwCompleted will have when the operation is complete.
            void SetProgress(
                uint dwCompleted, //DWORD
                uint dwTotal //DWORD
                );

            /// 

            /// Updates the progress dialog box with the current state of the operation.
            /// 

            /// An application-defined value that indicates what proportion of the operation has been completed at the time the method was called.
            /// An application-defined value that specifies what value ullCompleted will have when the operation is complete.
            void SetProgress64(
                ulong ullCompleted, //ULONGLONG
                ulong ullTotal //ULONGLONG
                );

            /// 

            /// Displays a message in the progress dialog.
            /// 

            /// 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.
            /// A null-terminated Unicode string that contains the text.
            /// TRUE to have path strings compacted if they are too large to fit on a line. The paths are compacted with PathCompactPath.
            ///  Reserved. Set to IntPtr.Zero.
            /// 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.
            void SetLine(
                uint dwLineNum, //DWORD
                [MarshalAs(UnmanagedType.LPWStr)] string pwzString, //LPCWSTR
                [MarshalAs(UnmanagedType.VariantBool)] bool fCompactPath, //BOOL
                IntPtr pvResevered //LPCVOID
                );

            /// 

            /// Sets a message to be displayed if the user cancels the operation.
            /// 

            /// A pointer to a null-terminated Unicode string that contains the message to be displayed.
            /// Reserved. Set to NULL.
            /// 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 ...". 
            void SetCancelMsg(
                [MarshalAs(UnmanagedType.LPWStr)] string pwzCancelMsg, //LPCWSTR
                object pvResevered //LPCVOID
                );

            /// 

            /// Resets the progress dialog box timer to zero.
            /// 

            /// Flags that indicate the action to be taken by the timer.
            /// Reserved. Set to NULL.
            /// 
            /// 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.
            void Timer(
                PDTIMER dwTimerAction, //DWORD
                object pvResevered //LPCVOID
                );

        }

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

        /// 

        /// Flags that indicate the action to be taken by the ProgressDialog.SetTime() method.
        /// 

        public enum PDTIMER : uint //DWORD
        {
            /// 
Resets the timer to zero. Progress will be calculated from the time this method is called.

            Reset = (0x01),
            /// 
Progress has been suspended.

            Pause = (0x02),
            /// 
Progress has been resumed.

            Resume = (0x03)
        }

        [Flags]
        public enum PROGDLG : uint //DWORD
        {
            /// 
Normal progress dialog box behavior.

            Normal = 0x00000000,
            /// 
The progress dialog box will be modal to the window specified by hwndParent. By default, a progress dialog box is modeless.

            Modal = 0x00000001,
            /// 
Automatically estimate the remaining time and display the estimate on line 3. 

            /// If this flag is set, IProgressDialog::SetLine can be used only to display text on lines 1 and 2.
            AutoTime = 0x00000002,
            /// 
Do not show the "time remaining" text.

            NoTime = 0x00000004,
            /// 
Do not display a minimize button on the dialog box's caption bar.

            NoMinimize = 0x00000008,
            /// 
Do not display a progress bar.

            /// 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.
            NoProgressBar = 0x00000010
        }
        #endregion
    }
}