当前位置: 首页 > 编程语言 > C#

如何将焦点设置到已经运行的应用程序?分享

时间:2023-04-10 19:09:20 C#

如何将焦点设置到已经运行的应用程序?我开发了一个C#windows应用程序并创建了它的exe。我想要的是,当我尝试运行该应用程序时,如果它已经处于运行状态而不是激活该应用程序,请打开新应用程序,这意味着我不想多次打开同一个应用程序使用以下代码设置为当前应用程序:[DllImport("user32.dll")]internalstaticexternIntPtrSetForegroundWindow(IntPtrhWnd);[DllImport("user32.dll")]internalstaticexternboolShowWindow(IntPtrhWnd,intnCmdShow);...进程currentProcess=Process.GetCurrentProcess();IntPtrhWnd=currentProcess.MainWindowHandle;如果(hWnd!=IntPtr.Zero){SetForegroundWindow(hWnd);ShowWindow(hWnd,User32.SW_MAXIMIZE);您可以从user32.dllSetForegroundWindow()和SetFocus()调用PInvoke来执行此操作。[DllImport("user32.dll")]staticexternboolSetForegroundWindow(IntPtrhWnd);//SetFocus只会将键盘聚焦在您的应用程序上,但不会将您的流程置于最前面。//这里不需要,SetForegroundWindow也是一样的。//仅用于文档。[DllImport("user32.dll")]staticexternIntPtrSetFocus(HandleRefhWnd);作为参数,您传递要置于前面和焦点的过程的窗口句柄。SetForegroundWindow(myProcess.MainWindowHandle);SetFocus(newHandleRef(null,myProcess.Handle));//不需要另请参阅msdna上SetForegroundWindow方法的限制。使用Mutex启动应用程序的单个实例。此外,您可以使用Process类找到您的应用程序并在其上设置焦点。此处http://social.msdn.microsoft.com/Forums/da-DK/csharpgeneral/thread/7fd8e358-9709-47f2-9aeb-6c35c7521dc3使用以下代码部分对exe进行多实例检查,它在表单加载时为真返回。要在您的应用程序中运行此功能,请使用System.Diagnostics;namespace以上是C#学习教程:如何将焦点设置到已经运行的应用程序?如果分享的内容对你有用,需要了解更多C#学习教程,希望你多多关注—privateboolCheckMultipleInstanceofApp(){boolcheck=false;进程[]prc=null;串ModName,ProcName;ModName=Process.GetCurrentProcess().MainModule.ModuleName;ProcName=System.IO.Path.GetFileNameWithoutExtension(ModName);prc=Process.GetProcessesByName(ProcName);if(prc.Length>1){MessageBox.Show("有一个正在运行的应用程序实例");检查=真;系统.环境.退出(0);}退货支票;}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: