我已经将我的C# windows应用程序限制为一次只允许一个实例运行,使用这个问题How to force C# .net app to run only one instance in Windows?
它工作良好,不允许应用程序的多个实例同时运行。
问题是,如果用户试图打开应用程序的第二个实例,我希望当前活动的实例出现在前面。
我所提出的问题似乎是为了解决这个问题,但它并不适用于我。
我认为这是因为我的应用程序不符合允许方法:SetForegroundWindow工作的条件。
我的问题是,我怎样才能做到这一点。我的代码如下:
using System ;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace RTRFIDListener_Client
{
static class Program
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
bool createdNew = true;
using (Mutex mutex = new Mutex(true, "RTRFIDListener_Client", out createdNew))
{
if (createdNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frm_Main());
}
else
{
Process current = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(current.ProcessName))
{
if (process.Id != current.Id)
{
SetForegroundWindow(process.MainWindowHandle);
break;
}
}
}
}
}
}
}发布于 2015-03-25 16:07:20
旋转您自己的单实例应用程序通常是一个错误,.NET框架已经强大地支持它,它是坚如磐石的,很难利用。并且有你要寻找的功能,一个StartupNextInstance事件,当用户再次启动你的应用程序时触发它。添加对Microsoft.VisualBasic的引用,并使Program.cs文件看起来如下所示:
using System;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;
namespace WhatEverYouUse {
class Program : WindowsFormsApplicationBase {
[STAThread]
static void Main(string[] args) {
Application.SetCompatibleTextRenderingDefault(false);
new Program().Start(args);
}
void Start(string[] args) {
this.EnableVisualStyles = true;
this.IsSingleInstance = true;
this.MainForm = new Form1();
this.Run(args);
}
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs) {
eventArgs.BringToForeground = true;
base.OnStartupNextInstance(eventArgs);
}
}
}如果使用用于启动第二个实例的命令行参数(例如,在使用文件关联时是典型的),则在事件处理程序中使用eventArgs.CommandLine。
发布于 2017-11-20 13:33:37
试试这个..。
System.Threading.Tasks.Task.Factory.StartNew(() => { SetForegroundWindow(this.Handle); });https://stackoverflow.com/questions/29260084
复制相似问题