4

I want my form to start up and open in the center relative to window that was active when my form was called. Say if Firefox was active and I display the form, I'd like my form to be shown in the "center" of the firefox window.

I think one way I can achieve this is by using SetWindowPos from user32.dll, but I'm not too sure if there is an easier way.

I have already played around with SetWindowPos and found that I can easily center my window on the whole screen, but I'm not too sure about where I should start to work on centering it relative to another window.

Basically, I will need to:

  1. Grab window location/size
  2. Do the math to find the coordinates in center minus my form size to prep
  3. Show my form and use set window pos to position it correctly?

Note: CenterParent will not work for this, it seems to only work for another Form control. I want to use this with other windows, like Firefox for example.

1 Answer 1

2

If you want center the new window relative to parent window, then you can set the "StartPosition" of the child form to "CenterParent". If you want center the new window relative to some other window then i think you have handle the Windows API.

[DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); private IntPtr GetActiveWindow() { IntPtr handle = IntPtr.Zero; return GetForegroundWindow(); } Then get the window position with GetWindowRect. [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect); [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left; // x position of upper-left corner public int Top; // y position of upper-left corner public int Right; // x position of lower-right corner public int Bottom; // y position of lower-right corner } 
Sign up to request clarification or add additional context in comments.

7 Comments

Again this doesn't seem to work relative to the window I have active. CenterParent seems to only work for a Windows Form control. When I try this on firefox it just starts in the very top-left corner of the screen.
@Steven Colgrove - I think you have to use user32.dll, to get the positon of the current active window. I you want the code for it well I can give you. :)
I don't think he means to center a window in the parent window but an arbitrary window.
Bibhu, I would love an example for that. I'm not very experienced at using external calls like these.
Thank you a lot for this. I will paste back any additions I make that will allow me to get into the center of this window :D
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.