【发布时间】:2014-03-11 00:47:07
【问题描述】:
我一直在尝试用 C# 编写一个简单的程序,以启动不同的软件,并将其移动到特定的屏幕,以便能够在总共有 12 个显示器的机器上自动设置不同的窗口。
这些窗口中的大多数都是在 Chrome 或 Internet Explorer 中启动的。
我用来移动应用程序的代码如下:
[DllImport("User32.dll")]
static extern 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);
它似乎在记事本上工作得很好,但是当它是一个浏览器时,MainWindowHandle 总是返回 IntPtr.Zero,即使我刷新了进程。
有什么建议吗?
【问题讨论】:
-
几个错误。您的 Console.WriteLine() 调用已损坏,您需要附加 this.process.MainWindowHandle.ToInt64()。请改用调试器。您的 SetWindowPos() 已损坏、错误的 pinvoke 声明和错误的使用。请改用 MoveWindow(),访问 pinvoke.net 网站以获得良好的声明。
-
谢谢。我会看看 pinvoke.net。我对 C# 不是很熟悉。 :)
-
MoveWindow 也适用于记事本。但是,它不适用于 Chrome,因为 process.MainWindowHandle.ToInt64() 返回 IntPtr.Zero 。 process.Handle 返回进程的有效 ID。
-
联系 Google 寻求支持。或者使用 iexplore.exe
-
@Drejer 我的回答对你有帮助吗?
标签: c# winapi window-handles