我有一个应用程序,一次只能打开一个自己的实例.为了强制执行此操作,我使用以下代码:
System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcesses(); System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess(); foreach (System.Diagnostics.Process p in myProcesses) { if (p.ProcessName == me.ProcessName) if (p.Id != me.Id) { //if already running, abort this copy. return; } } //launch the application. //...
它工作正常.我还希望它能够集中已经运行的副本的形式.也就是说,在返回之前,我想将此应用程序的其他实例置于前台.
我怎么做?
Re:SetForeGroundWindow:
SetForeGroundWindow工作,到一点:
[System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd); //... if (p.Id != me.Id) { //if already running, focus it, and then abort this copy. SetForegroundWindow(p.MainWindowHandle); return; } //...
如果窗口没有最小化,这会将窗口置于前台.真棒.但是,如果窗口IS最小化,它将保持最小化.
它需要取消最小化.
通过SwitchToThisWindow解决方案(Works!):
[System.Runtime.InteropServices.DllImport("user32.dll")] public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab); [STAThread] static void Main() { System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess(); System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName(me.ProcessName); foreach (System.Diagnostics.Process p in myProcesses) { if (p.Id != me.Id) { SwitchToThisWindow(p.MainWindowHandle, true); return; } } //now go ahead and start our application ;-)
scottm.. 10
我有同样的问题,SwitchToThisWindow()对我来说效果最好.唯一的限制是您必须安装XP sp1.我玩SetForegroundWindow,ShowWindow,他们都有问题拉窗口进入视图.
我有同样的问题,SwitchToThisWindow()对我来说效果最好.唯一的限制是您必须安装XP sp1.我玩SetForegroundWindow,ShowWindow,他们都有问题拉窗口进入视图.