开发者

FolderNameEditor.FolderBrowser with FolderBrowserStyles.ShowTextBox - Automatically create new folder from TextBox.Text

I'm showing a FolderBrowser to the user in my application and then promotes him with a ShowDialog() which has m_dialog.Style = FolderBrowserStyles.ShowTextBox; Thus, allowing the user to manually enter path for the folder he wants to choose.

The problem is that when the user types a path for a folder which doesn't exists and clicks OK, the dialog returns with some default DirectoryPath value. What I want is the selected folder to be created (if it doesn't exists, and by promoting the user first) and then have the (now valid) path inside the DirectoryPath property.

Any开发者_StackOverflow社区 way to do it?


The FolderNameEditor.FolderBrowser class makes use of the SHBrowseForFolder shell function. The default functionality based on the user entering an invalid path is to return the default selected item (which in this case is the Desktop folder).

The SHBrowseForFolder shell function expects an argument of type BROWSEINFO (structure).

This structure allows for the definition of a callback function (a pointer to an application-defined function that the dialog box calls when an event occurs) and it is in this callback that the possibility lies of achieving what you require.

This callback function is set to null when FolderBrowser invokes this shell function, so there is no possible way of achieving what you require using the FolderNameEditor class.

However there is a library on codeproject you can make use of which uses the SHBrowseForFolder and wraps the event callback, providing access to the invalid folder entry through an event (OnValidateFailed). See: C# does Shell, Part 1

Within this event (after some validation (as the user can input anything)) you could use the path entered to create the directory.

Here is an example:

using ShellLib;

...

public class OpenFolderDialog
{
    ShellBrowseForFolderDialog folderDialog;
    string selectedPath;

    public OpenFolderDialog()
    {
        folderDialog = new ShellBrowseForFolderDialog();
        folderDialog.OnValidateFailed += new ShellBrowseForFolderDialog.ValidateFailedHandler(dialog_OnValidateFailed);
    }

    int dialog_OnValidateFailed(ShellBrowseForFolderDialog sender, ShellBrowseForFolderDialog.ValidateFailedEventArgs args)
    {
        selectedPath = args.invalidSel;

        //Use selectedPath here to create the directory.

        return 0;
    }

    public string GetFolder()
    {
        selectedPath = string.Empty;
        folderDialog.ShowDialog();

        return selectedPath == string.Empty ? folderDialog.FullName : selectedPath;
    }
}

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜