我怎么能执行我的应用程序的一个实例?

编程入门 行业动态 更新时间:2024-10-27 19:23:09
本文介绍了我怎么能执行我的应用程序的一个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何确保我的应用程序的一个实例,并试图打开第二个实例时,焦点设置呢?

How can I ensure a single instance of my application and to set the focus to it when attempting to open a second instance?

我想:

public partial class Form1 : Form { [DllImport("USER32.DLL", CharSet = CharSet.Unicode)] public static extern IntPtr FindWindow(String lpClassName, String lpWindowName); [DllImport("USER32.DLL")] public static extern Boolean SetForegroundWindow(IntPtr hWnd); private void Form1_Load(object sender, EventArgs e) { bool isRunning = Process.GetProcesses() .Where(p => p.MainWindowTitle.Contains(Text)) .Count() > 1; if (isRunning) { FocusWindow(Text); Application.Exit(); } } public static void FocusWindow(string title) { SetForegroundWindow(FindWindow(null, title)); } }

这是重点不在于应用。我该如何解决这个问题?

This is not focusing the application. How can I fix this?

推荐答案

您可能需要使用互斥代替,避免了搜索窗口在一个稍微不可靠的方式(想象你重命名你的主要形式或打开另一种形式代替)。

You may want to use Mutex instead, which avoids to search for windows in a slightly unreliable way (imagine you rename your main form or open another form instead).

bool createdNew; Mutex m = new Mutex(true, "SomeNameHere", out createdNew); if (!createdNew) { // Application already running. Call it and ask to show it's form. IpcClientChannel clientChannel = new IpcClientChannel(); ChannelServices.RegisterChannel(clientChannel, true); RemotingConfiguration.RegisterWellKnownClientType(typeof(ExchangeBase), "ipc://SomeNameHere/YourAppBase"); ExchangeBase Exchange = new ExchangeBase(); Exchange.ShowForm(); } else { IpcServerChannel serverChannel = new IpcServerChannel("SomeNameHere"); ChannelServices.RegisterChannel(serverChannel, true); RemotingConfiguration.RegisterWellKnownServiceType(typeof(ExchangeBase), "YourAppBase", WellKnownObjectMode.SingleCall); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); MainForm = new FormMain(); if (!MainForm.StopLoading) { Application.Run(MainForm); // Keep the mutex reference alive until the termination of the program. GC.KeepAlive(m); } }

更多推荐

我怎么能执行我的应用程序的一个实例?

本文发布于:2023-11-16 02:42:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1600275.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:应用程序   实例   我怎么能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!