Joe Almore Joe Almore - 4 months ago 56
C# Question

C# Move Windows In Sync

I have one simple C# application which opens another process. What I want is to move the Main Window of that opened process as I move the C# application. By now, what I have is this code:

[DllImport("user32.dll", SetLastError = true)]
internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

It works to move the Window of the Process, but how do I get the event to move both windows in sync, so one moves as the other moves?


The easiest way is to move your other form when the C# form moves, which you can detect by adding a handler for the Control.Move event:

private void ControlMovedHandler(object sender, EventArgs e)
    MoveWindow(otherWindowHandle, Location.X, Location.Y, ...);

You can use the form editor to automatically add the event handler to the main form.

As far as getting your window to move when the other one does, it's much more difficult; one way would be to have a timer/loop constantly check to see if the other window's position changed, then move yourself accordingly. Also, you need to be careful that you don't get stuck in an infinite loop of moving the windows to the same location (i.e. A moves, which moves B, which then tries to move A, which then tries to move B, etc).