How to center OpenFileDialog in its parent window in WPF?

I am using WPF OpenFileDialog and I am looking for a way to make sure that it is centered in the parent window when shown. It seems that there are no obvious properties, such as StartupPosition, that can enable this.

Does anyone know a secret?

Update: It seems that the first time I open it, it appears in the center of the parent, but if I translate it, it then remembers its position and does not open with the center on subsequent occasions.

+3
source share
2 answers

here is the code for a universal class that allows you to play with "helper dialogs" like this one:

public class SubDialogManager : IDisposable
{
    public SubDialogManager(Window window, Action<IntPtr> enterIdleAction)
        :this(new WindowInteropHelper(window).Handle, enterIdleAction)
    {
    }

    public SubDialogManager(IntPtr hwnd, Action<IntPtr> enterIdleAction)
    {
        if (enterIdleAction == null)
            throw new ArgumentNullException("enterIdleAction");

        EnterIdleAction = enterIdleAction;
        Source = HwndSource.FromHwnd(hwnd);
        Source.AddHook(WindowMessageHandler);
    }

    protected HwndSource Source { get; private set; }
    protected Action<IntPtr> EnterIdleAction { get; private set; }

    void IDisposable.Dispose()
    {
        if (Source != null)
        {
            Source.RemoveHook(WindowMessageHandler);
            Source = null;
        }
    }

    private const int WM_ENTERIDLE = 0x0121;

    protected virtual IntPtr WindowMessageHandler(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        if (msg == WM_ENTERIDLE)
        {
            EnterIdleAction(lParam);
        }
        return IntPtr.Zero;
    }
}

WPF. , : -)

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        bool computed = false; // do this only once
        int x = (int)Left;
        int y = (int)Top;
        int w = (int)Width;
        int h = (int)Height;
        using (SubDialogManager center = new SubDialogManager(this, ptr => { if (!computed) { SetWindowPos(ptr, IntPtr.Zero, x, y, w, h, 0); computed= true; } }))
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.ShowDialog(this);
        }
    }

    [DllImport("user32.dll")]
    private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, int flags);
}
+5

CommonDialog WPF , StartupPosition.

: OpenFileDialog .NET Vista
, , .

0

All Articles