允许该程序只有一个实例时,从系统托盘还原窗口 [英] Restoring window from the system tray when allowing only one instance of that program
问题描述
OK,标题是很长,应该告诉我现在面临的问题。
ok, the title is pretty long and should tell the problem i'm facing with.
下面是代码以最小化托盘图标时:
Here is the code when minimizing to icon tray:
void MainFormResize(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized)
{
this.Hide();
this.ShowInTaskbar = false;
}
}
当程序已经打开,并在sys盘,仍然有人想打开它的另一个实例,则:
When the program is already opened and in sys tray, and still someone wants to open another instance of it, then:
private static void Main(string[] args)
{
bool createdNew = true;
using (Mutex mutex = new Mutex(true, "IPADcommunicator", out createdNew))
{
if (createdNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
else
{
Process current = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(current.ProcessName))
{
if (process.Id != current.Id)
{
IntPtr handle = FindWindow(null,"IPADcommunicator");
SetForegroundWindow(handle);
ShowWindow(handle,5);
break;
}
}
...
Howeve,它是工作不正常。在主窗口不会恢复。
我GOOGLE了很多,还没有找到这个问题的解决方案。提前
谢谢!
Howeve, it is not working properly. The mainwindow is not restored. I've googled a lot and haven't found solutions for that problem. Thanks in advance!
推荐答案
调用SetForegroundWindow()是行不通的。还有许多其他可能的故障模式,FindWindow函数()是一个悲惨的之一,当你开始传递空。
Calling SetForegroundWindow() on an invisible window isn't going to work. There are many other possible failure mode, FindWindow() is a miserable one when you start passing null.
不要发明这个自己,.NET已经内置很大在单实例应用程序的支持。你甚至可以得到一个通知第二副本启动时,并通过命令行。这是你想要的这里,简直恢复黑客API的窗口,而不是。该代码你需要是这里。
Don't invent this yourself, .NET already has great built-in support for single instance apps. You can even get a notification when a 2nd copy starts and pass the command line. Which is what you want here, simply restore the window instead of hacking the API. The code you need is here.
这篇关于允许该程序只有一个实例时,从系统托盘还原窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!