我一直在尝试用C#创建一个简单的程序,以启动不同的软件,并将其移至特定的屏幕,以便能够在总共有12个监视器的计算机上自动设置不同的窗口。
这些窗口中的大多数是在Chrome或Internet Explorer中启动的。
我用来移动应用程序的代码如下:[DllImport(“ User32.dll”)]静态外部int SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);
this.process = Process.Start(this.startInfo);
process.WaitForInputIdle();
SetForegroundWindow(this.process.MainWindowHandle);
Console.WriteLine("Process ID: "+ this.process.Handle);
this.process.Refresh();
Console.WriteLine("Main window handle: " + this.process.MainWindowHandle);
Point screenlocation = Screen.AllScreens[MonitorNum].Bounds.Location;
SetWindowPos(this.process.MainWindowHandle, -1, screenlocation.X, screenlocation.Y, Screen.AllScreens[MonitorNum].Bounds.Width, Screen.AllScreens[MonitorNum].Bounds.Height, 1);
使用Notepad似乎工作正常,但是当它是浏览器时,MainWindowHandle始终返回IntPtr.Zero,即使我刷新了Process。
有什么建议吗?
现代浏览器使用复杂的多进程体系结构。
如果在启动新的chrome.exe进程时chrome进程已经在运行,则两个进程之间会发生一些进程间通信,并且会启动新的子进程(旧的现有进程的子进程)来承载新的标签页渲染。您启动的进程然后立即退出,您无法为该已死进程获取一个主窗口。创建新的Chrome主窗口是预先存在的过程。
您可以尝试使用以下C ++源代码
#include <Windows.h>
#include <stdio.h>
int main( void ) {
STARTUPINFO SI;
memset( &SI, 0, sizeof SI );
SI.cb = sizeof SI;
PROCESS_INFORMATION PI;
BOOL bWin32Success =
CreateProcess( L"C:\\Users\\manuel\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe",
NULL, NULL, NULL, FALSE, 0, NULL,
L"C:\\Users\\manuel\\AppData\\Local\\Google\\Chrome\\Application",
&SI, &PI );
if ( bWin32Success ) {
printf( "PID %u\n", PI.dwProcessId );
DWORD dwRet = WaitForInputIdle( PI.hProcess, 1000 );
switch ( dwRet ) {
case 0:
printf( "WaitForInputIdle succeedeed\n" );
break;
case WAIT_TIMEOUT:
printf( "WaitForInputIdle timed out\n" );
break;
case WAIT_FAILED:
printf( "WaitForInputIdle Error %u\n", GetLastError() );
break;
default:
printf( "WaitForInputIdle Unknown return value %d\n", dwRet );
}
CloseHandle( PI.hThread );
CloseHandle( PI.hProcess );
} else {
printf( "CreateProcess Error %u\n", GetLastError() );
}
return 0;
}
使用Spy ++和Windows Task Manager或更好的Process Explorer,您将看到,当chrome已在运行时,新的Chrome主窗口由已运行的chrome.exe托管,并且启动的进程CreateProcess
将终止。
解:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句