[WPF]程序重复运行时激活上次运行的实例
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2017-08-27 10:47:21
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章
打开启动程序的App.xaml.cs文件加入下面代码
[DllImport("user32", CharSet = CharSet.Unicode)]
static extern IntPtr FindWindow(string cls, string win);
[DllImport("user32")]
static extern IntPtr SetForegroundWindow(IntPtr hWnd);
[DllImport("user32")]
static extern bool IsIconic(IntPtr hWnd);
[DllImport("user32")]
static extern bool OpenIcon(IntPtr hWnd);
System.Threading.Mutex mutex;
public App()
{
this.Startup += new StartupEventHandler(App_Startup);
}
void App_Startup(object sender, StartupEventArgs e)
{
bool ret;
//下面的RemoteDesktop改成自己项目名字或喜欢的一个标识
mutex = new System.Threading.Mutex(true, "RemoteDesktop", out ret);
if (!ret)
{
MessageBox.Show("已有一个程序实例运行");
ActivateOtherWindow();
Environment.Exit(0);
}
}
private static void ActivateOtherWindow()
{
//里面的文本改成自己程序窗口的标题
var other = FindWindow(null, "远程桌面管理工具");
if (other != IntPtr.Zero)
{
SetForegroundWindow(other);
if (IsIconic(other))
OpenIcon(other);
}
}