WinForm 限制同一个进程只能打开一次
生活随笔
收集整理的這篇文章主要介紹了
WinForm 限制同一个进程只能打开一次
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
打開?Program.cs 代碼文件,這里是程序的入口點,如下:
static void Main(){ Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(new frMain()); }經過以下修改,就可以實現同一個進程只能打開一次的效果:
static void Main() {Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);//1.這里判定是否已經有實例在運行//只運行一個實例Process instance = RunningInstance();if (instance == null){//1.1 沒有實例在運行Application.Run(new FrMain()); }else{//1.2 已經有一個實例在運行HandleRunningInstance(instance);}}//2.在進程中查找是否已經有實例在運行 private static Process RunningInstance(){Process current = Process.GetCurrentProcess();Process[] processes = Process.GetProcessesByName(current.ProcessName);//遍歷與當前進程名稱相同的進程列表foreach (Process process in processes){//如果實例已經存在則忽略當前進程if (process.Id != current.Id){//保證要打開的進程同已經存在的進程來自同一文件路徑if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName){//返回已經存在的進程return process;}}}return null;}//3.已經有了就把它激活,并將其窗口放置最前端 private static void HandleRunningInstance(Process instance){ShowWindowAsync(instance.MainWindowHandle, 1); //調用api函數,正常顯示窗口SetForegroundWindow(instance.MainWindowHandle); //將窗口放置最前端}[DllImport("User32.dll")]private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);[DllImport("User32.dll")]private static extern bool SetForegroundWindow(System.IntPtr hWnd);
總結
以上是生活随笔為你收集整理的WinForm 限制同一个进程只能打开一次的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#反射调用 异常信息:Ambiguou
- 下一篇: 以和谐为基础取广场名字