如何从 WinForms 应用程序控制新进程窗口的大小和位置?

问题描述:

我的 WinForms 应用程序使用 Process.Start() 在其原生应用程序中打开文件.我想将屏幕一分为二,一边显示我的 WinForms 应用程序,另一边显示新进程.我知道我可以使用 Process.MainWindowHandle 来获取窗口句柄,但是如何设置它的大小和位置?

My WinForms app uses Process.Start() to open files in their native app. I want to split the screen in half, showing my WinForms app on one half and the new process on the other. I know I can use Process.MainWindowHandle to get the window handle, but how can I set its size and position?

我想我必须使用某种 Windows API,但使用哪一种以及如何使用?由于这并不是真正在我的驾驶室",我不确定我是否(以及如何)需要在 64 位 Windows 上使用不同的 API.

I imagine I have have to use some kind of Windows API, but which one and how? Since this is not really "in my wheelhouse", I am unsure of whether (and how) I need to use different APIs on 64bit Windows.

有问题的 Windows API 方法是 SetWindowPos.你可以这样声明:

The Windows API method in question is SetWindowPos. You can declare it like so:

[DllImport("user32.dll")]
private extern static bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);

并在此处阅读:http://msdn.microsoft.com/en-us/library/ms633545.aspx

已添加

Process.MainWindowHandle 是您将使用的 hWnd 参数.hWndInsertAfter 可能是您自己的表单句柄 (Form.Handle).您可以使用屏幕类型访问有关桌面的信息:http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.aspx

Process.MainWindowHandle is the hWnd parameter you will use. hWndInsertAfter will probably be your own Form's handle (Form.Handle). You can use the Screen type to access information about the desktop: http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.aspx

添加了托马斯的评论

在调用 SetWindowPos 之前确保您 WaitForInputIdle.

Make sure you WaitForInputIdle before calling SetWindowPos.

Process process = Process.Start(...);
if (process.WaitForInputIdle(15000))
    SetWindowPos(process.MainWindowHandle, this.Handle, ...);

上述 SetWindowPos 声明适用于 32 位和 64 位 Windows.

The declaration for SetWindowPos above works for both 32- and 64-bit Windows.