Form shown from the main UI thread is not centered within the parent but it does from a timer

111 Views Asked by At

I have an WPF UserControl which is embedded within an elementhost so I can show it in a winforms application. I have a class that inherits from Form.This class contains the elementhost which in turn embeds the WPF control. I am trying to center this form within the parent window but without success. See below code I use (the class where I have this method is the Form).

When trying to get the handle of the parent window, I get a valid parentWindowHandle Id but parentWindow gets null (see below code).

Also within that method I have checked what is the value for base.StartPosition and it is FormStartPosition.CenterParent.

    private DialogResult ShowAsChild(bool showDialog = false)
    {
        NativeWindow parentWindow = null;
        try
        {
            IntPtr parentWindowHandle = Process.GetCurrentProcess().MainWindowHandle;
            parentWindow = NativeWindow.FromHandle(parentWindowHandle);
        }
        catch (Exception ex)
        {
            parentWindow = null;
        }
        
        if (parentWindow != null)
        {
            if (showDialog)
            {
                return base.ShowDialog(parentWindow);
            }
            else
            {
                base.Show(parentWindow);
            }
        }
        else
        {
            if (showDialog)
            {
                return base.ShowDialog();
            }
            else
            {
                base.Show();
            }
        }

        return DialogResult.None;
    }

I am calling the above method and showing the child window from the main UI thread and it is not working, child window is not centered within the parent. However, if I call the above method and show the child window from a timer, then it is centered correctly within the parent. The code executed in both cases is the same. The only difference is that one is executed from the main UI thread, and the other from a System.Windows.Forms.Timer, but in fact, when you execute code from a timer it also runs from the main UI thread, so I don't understand why it is hapenning.

Any ideas will be highly appreciated.

0

There are 0 best solutions below