将过程放入容器表单中

本文关键字:表单 过程 | 更新日期: 2023-09-27 18:09:41

我想在我的c#应用程序中启动一个进程,我可以通过使用以下代码来实现:

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "chrome.exe";
startInfo.WorkingDirectory = @"C:'Program Files'Google'Chrome'Application";
Process process = Process.Start(startInfo);

但是当我打开这个时,它在整个屏幕上打开,意味着它覆盖了整个屏幕。我需要它被包含在我的表单的边界内。假设表单的大小是906, 495,那么这个应用程序应该在这个区域内打开。

我找不到我该怎么做。其次,我需要设置任何应用程序的大小。就像我用过Chrome,但它可能是任何其他进程。这可能吗?

将过程放入容器表单中

你可以这样做:

[DllImport("user32.dll", SetLastError = true)]
internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "chrome.exe";
startInfo.WorkingDirectory = @"C:'Program Files'Google'Chrome'Application";
//Force chrome to run in a new process
startInfo.Arguments = @"--user-data-dir=C:'sometempdir";
Process process = Process.Start(startInfo);
process.WaitForInputIdle();
//Need to do a little more work make sure we get the Window handle properly
do
{
    System.Threading.Thread.Sleep(100);
    process.Refresh();
}
while (process.MainWindowHandle == IntPtr.Zero && !process.HasExited);  
//Set these appropriately
int xPos = 0;
int yPos = 0;
MoveWindow(process.MainWindowHandle, xPos, yPos, 906, 495, true);

正如mclaassen建议的那样,您应该使用MoveWindow API,但是您可能希望等到窗口显示:

        [DllImport("user32.dll", SetLastError = true)]
        internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName = "notepad.exe";
        Process process = Process.Start(startInfo);
        process.WaitForInputIdle(); // Wait for interface to load
        MoveWindow(process.MainWindowHandle, 0, 0, 100, 100, true);