Can I change the title of my FolderBrowserDialog?

我们两清 提交于 2019-12-04 22:28:32

You can't if you use the class FolderBrowserDialog directly. But I read somewhere that it could be possible to change the title with P/Invoke and sending WM_SETTEXT message.

In my opinion, it is not worth the pain. Just use the property Description to add the information:

FolderBrowserDialog dlg = new FolderBrowserDialog();
dlg.Description = "Select the document folder";

The simple answer is that you can't. The dialog displays using the standard title for a folder browser style dialog on Windows. The best option is to ensure that you have meaningful descriptive text by setting the Description property.

Even if you were to use P/Invoke to call the SHBrowseForFolder Win32 API function directly, the only option you still can't change the actual title of the dialog. You can set the lpszTitle field of the BROWSEINFO structure, which is

A pointer to a null-terminated string that is displayed above the tree view control in the dialog box. This string can be used to specify instructions to the user.

patzky

You can change it by using:

SetWindowText (hwnd, "Select a Folder");

Where hwnd is the window handle, which triggers the Browse For Folder Dialog.

I was looking up how to do this, but largely had to figure it out on my own. I hope this saves anyone some time:

Above my main method, I put:

    [DllImport("user32.dll", EntryPoint = "SetWindowText", CharSet = CharSet.Ansi)]
    public static extern bool SetWindowText(IntPtr hWnd, String strNewWindowName);
    [DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Ansi)]
    public static extern IntPtr FindWindow(string className, string windowName);

Since I know that the thread will pause while the dialog is shown, I created a new thread to check for that dialog window while it exists. Like so:

    bool notfound = true;
    new Thread(() => { 
    while (notfound)
    {
        //looks for a window with the title: "Browse For Folder"
        IntPtr ptr = FindWindow(null, "Browse For Folder");
        if (ptr != IntPtr.Zero)
        {
            //tells the while loop to stop checking
            notfound = false;
            //changes the title
            SetWindowText(ptr, "Be happy!");
        }
    }
    }).Start();

Then, I initiate the dialog:

    using (var fbd = new FolderBrowserDialog())
    {
        DialogResult result = fbd.ShowDialog();
        if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
        {
            //do stuff
        }
    }

This has worked for me, and it's not so complicated. Hope this helps anyone that might stumble on this page. By the way, remember that the thread must start before the dialog window is initiated, so that it can run and check for the window as soon as it exists.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!