private static Process RunningInstance() { Process current = Process.GetCurrentProcess(); Process[] processes = Process.GetProcessesByName(current.ProcessName);
foreach (Process process in processes) { if (process.Id!=current.Id) { if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\")==current.MainModule.FileName) { return process; } } }
只启动一个程序的实例:
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Reflection;
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Process instance = RunningInstance();
if (instance == null)
{
Application.Run(new Form1());
}
else
{
//MessageBox.Show("此程序已经启动!");
HandleRunningInstance(instance);
}
}
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
private const int WS_SHOWNORMAL = 1;
private static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
foreach (Process process in processes)
{
if (process.Id!=current.Id)
{
if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\")==current.MainModule.FileName)
{
return process;
}
}
}
return null;
}
private static void HandleRunningInstance(Process instance)
{
ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
SetForegroundWindow(instance.MainWindowHandle);
}
比如我选择了a.txt,b.txt,然后点击右键,选择我自己添加的菜单,启动程序,程序就显示我选择了哪些文件,列出文件名(a.txt,b.txt)