Search code examples
c#winformssolidworks

Center form in parent only having the parentWnd


i'm working with the Solidworks Pdm Api and i'm developing an addin using Windows Forms to show information about some files.

In the api docs, recommend to use this class to set the Pdm window as parent

public class WindowHandle : IWin32Window
{
    private IntPtr mHwnd;

    public WindowHandle(int hWnd)
    {
        mHwnd = new IntPtr(hWnd);
    }
    public IntPtr Handle
    {
        get { return mHwnd; }
    }
}

And it works well, so, when i will show my form, i'm doing the next

//i recived hWnd parameter from the api
WindowHandle myHandle = new WindowHandle(hWnd);
var weForm = new myForm();
weForm.StartPosition = FormStartPosition.CenterParent;
weForm.ShowDialog(myHandle);

At this point, the form shows without problem, the Pdm Window is effectively the parent, but the Form is not centered.

I found this question about how to center forms in his parent, but apparently anyone work when you use a custom class inherited from IWin32Window.

What can i do to center my form?


Solution

  • If the auto-centering feature isn't working then you'll need to do the math yourself.

    The math basically means that you align the center points of each window.

    int left = parentBounds.Left + (parentBounds.Width / 2) - (childBounds.Width / 2);
    int right = parentBounds.Top + (parentBounds.Height / 2) - (childBounds.Height / 2);