WPF 创建单例程序
App.xaml.cs:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
// Get Reference to the current Process
Process thisProc = Process.GetCurrentProcess();
// Check how many total processes have the same name as the current one
if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)
{
// If ther is more than one, than it is already running.
IntPtr intPtr = FindWindowW(null, "Files");//窗口名称
if (intPtr!=IntPtr.Zero)
{
SetForegroundWindow(intPtr);//设置到前台
}
Application.Current.Shutdown();
return;
}
base.OnStartup(e);
}
[DllImport("User32", CharSet = CharSet.Unicode)]
static extern IntPtr FindWindowW(string lpClassName, string LPCWSTR);//导入win32查找窗口函数
[DllImport("User32", CharSet = CharSet.Unicode)]
static extern Boolean SetForegroundWindow(IntPtr hWnd);//导入设置窗口前台显示函数
}