此文只是笔记,没什么技术内容,如有好的方法,请告知共享,呵呵
二话不说,上代码,示例如下:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;
namespace newestDotnetbar
{
static class Program
{
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("User32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
private const int WS_SHOWNORMAL = 1;
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Process instance = RunningInstance();
if (instance !=null)
{
HandleRunningInstance(instance);
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
FrmMain fm = new FrmMain();
fm.notifyIcon1.Visible = true;
Application.Run(fm);
}
}
public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
//Loop through the running processes in with the same name
foreach (Process process in processes)
{
if (process.Id != current.Id)
{
if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
{
//Return the other process instance.
return process;
}
}
}
//No other instance was found, return null.
return null;
}
public static void HandleRunningInstance(Process instance)
{
IntPtr hwnd = FindWindow(null, "xxx");//窗口类的Text名称
ShowWindowAsync(hwnd , WS_SHOWNORMAL);
//Set the real intance to foreground window
SetForegroundWindow(hwnd );
}
}
}