更新时间:2023-11-22 22:23:40
您可能需要使用互斥
代替,避免了搜索窗口在一个稍微不可靠的方式(想象你重命名你的主要形式或打开另一种形式代替)。
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);
}
}