我的应用程序有一个默认设置,当您启动计算机时,它会在图标托盘上运行。 如果您单击图标托盘中的图标,则该应用程序将显示在桌面窗口中。 此外,如果用户在旧应用程序运行时尝试启动我的应用程序的新实例,我只会显示一条消息,说明另一个实例正在运行,然后退出新实例。
现在我不仅要让新实例退出,还要使旧实例处于事件状态/显示在桌面上。 这是我现在的代码
if (System.Diagnostics.Process.GetProcessesByName(
System.Diagnostics.Process.GetCurrentProcess().ProcessName).Length > 1)
{
MessageBox.Show(kingCobra.Properties.Resources.Msg_Multiple_Starts,
kingCobra.Properties.Resources.Multiple_Starts,
MessageBoxButtons.OK, MessageBoxIcon.Warning);
System.Diagnostics.Process.GetCurrentProcess().Kill();
return;
}
最佳答案
你需要做的是将它添加到你的主类中:
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
然后您需要获取对已经运行的进程的引用,然后像这样调用 SetForegroundWindow 方法:
SetForegroundWindow(SameProcess.MainWindowHandle);
你不需要像你现在做的那样杀死当前进程,如上所示聚焦其他进程的主窗口后返回即可
这是一个完整的工作示例:
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
var currentProcess = Process.GetCurrentProcess();
foreach (Process p in Process.GetProcessesByName(currentProcess.ProcessName))
{
if (p.Id != currentProcess.Id)
{
MessageBox.Show("Already running");
SetForegroundWindow(p.MainWindowHandle);
return;
}
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
关于c# - 只运行一个应用程序实例,(退出新实例并显示旧实例或给予焦点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18510082/