Setting the start position for OpenFileDialog/SaveFileDialog

前端 未结 8 1712
野趣味
野趣味 2021-01-01 11:48

For any custom dialog (form) in a WinForm application I can set its size and position before I display it with:

form.StartPosition = FormStartPosition.Manual         


        
8条回答
  •  余生分开走
    2021-01-01 12:22

    Here's how I did it:

    The point where I want to display the OpenFileDialog:

    Thread posThread = new Thread(positionOpenDialog);
    posThread.Start();
    
    DialogResult dr = ofd.ShowDialog();
    

    The repositioning code:

    [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
    static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
    
    [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
    public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);
    
    
    /// 
    /// Find the OpenFileDialog window when it appears, and position it so
    /// that we can see both dialogs at once.  There is no easier way to
    /// do this (&^%$! Microsoft!).
    /// 
    private void positionOpenDialog ()
    {
        int count = 0;
        IntPtr zero = (IntPtr)0;
        const int SWP_NOSIZE = 0x0001;
        IntPtr wind;
    
        while ((wind = FindWindowByCaption(zero, "Open")) == (IntPtr)0)
            if (++count > 100)
                return;             // Find window failed.
            else
                Thread.Sleep(5);
    
        SetWindowPos(wind, 0, Right, Top, 0, 0, SWP_NOSIZE);
    }
    

    I start a thread that looks for a window with the "Open" title. (Typically found in 3 iterations or 15 milliseconds.) Then I set its position with the obtained handle. (See SetWindowPos documentation for the position/size parameters.)

    Kludgy.

提交回复
热议问题