如何确保我的应用程序只有一个实例,并在尝试打开第二个实例时将焦点设置到它?
我试过:
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));
}
}
这不是聚焦应用。我该如何解决这个问题?
最佳答案
您可能想改用 Mutex
,这样可以避免以稍微不可靠的方式搜索窗口(假设您重命名主窗体或打开另一个窗体)。
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);
}
}
关于c# - 我怎样才能执行我的应用程序的单个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8856441/