How to replace FileName in SaveFileDialog.FileOk event handler

二次信任 提交于 2019-12-24 06:43:59

问题


I'd like to change the file name of the SaveFileDialog in the event handler attached to the FileOk event, in order to replace the file name typed in by the user with another file name in some cases, while keeping the dialog open:

var dialog = new SaveFileDialog();
...
dialog.FileOk +=
    delegate (object sender, CancelEventArgs e)
    {
        if (dialog.FileName.EndsWith (".foo"))
        {
            dialog.FileName = "xyz.bar";
            e.Cancel = true;
        }
    };

Stepping through the code shows that the FileName gets indeed properly updated, but when the event handler returns, the file name displayed in the dialog does not change. I've seen that I could theoretically use Win32 code like the following to change the file name in the dialog itself:

class Win32
{
   [DllImport("User32")]
   public static extern IntPtr GetParent(IntPtr);

   [DllImport("User32")]
   public static extern int SetDlgItemText(IntPtr, int string, int);

   public const int FileTitleCntrlID = 0x47c;
}

void SetFileName(IntPtr hdlg, string name)
{
    Win32.SetDlgItemText (Win32.GetParent (hdlg), Win32.FileTitleCntrlID, name);
}

However, I've no idea where I can get the HDLG associated to the SaveFileDialog instance from. I know I can rewrite the whole SaveFileDialog wrapper myself (or use code like NuffSaveFileDialog or the CodeProject extension of SaveFileDialog), but I'd prefer to use the standard WinForms classes for technical reasons.


回答1:


to get the dialog handle I used reflection, then called SetFileName with that handle:

dialog.FileOk +=
    delegate (object sender, CancelEventArgs e)
    {
        if (dialog.FileName.EndsWith (".foo"))
        {
            Type type = typeof(FileDialog);
            FieldInfo info = type.GetField("dialogHWnd", BindingFlags.NonPublic 
                                                       | BindingFlags.Instance);
            IntPtr fileDialogHandle = (IntPtr)info.GetValue(dialog);

            SetFileName(fileDialogHandle, "xyz.bar");
            e.Cancel = true;
        }
    };

N.B.: in your Win32 class you only need to define SetDlgItemText function (there is no need to GetParent) and pass to it the dialog handle:

    [DllImport("User32")]
    public static extern int SetDlgItemText(IntPtr hwnd, int id, string title);

    public const int FileTitleCntrlID = 0x47c;

    void SetFileName(IntPtr hdlg, string name)
    {
        SetDlgItemText(hdlg, FileTitleCntrlID, name);
    }

EDIT:

To have the previous code working on Windows 7 (Vista also I think?), set the dialog's property ShowHelp to true:

dialog.ShowHelp = true;

the appearance will change a little bit, but I don't think it's a big deal.



来源:https://stackoverflow.com/questions/1599511/how-to-replace-filename-in-savefiledialog-fileok-event-handler

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