当前位置: 首页 > news >正文

C#/WPF 只允许一个实例程序运行并将已运行程序置顶

使用用互斥量(System.Threading.Mutex):
    同步基元,它只向一个线程授予对共享资源的独占访问权。在程序启动时候,请求一个互斥体,如果能获取对指定互斥的访问权,就职运行一个实例。

实例代码:

    /// <summary>/// App.xaml 的交互逻辑/// </summary>public partial class App : Application{[DllImport("user32.dll ")]//设置窗体置顶private static extern bool SetForegroundWindow(IntPtr hWnd);[DllImport("User32.dll")]public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);private static Mutex _m = null;private static string currentProcess = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;/// <summary>/// 只允许运行一个实例/// </summary>/// <param name="mutexName"></param>/// <returns>true:已经存在实例 false:不存在实例</returns>public static bool CheckRunOneInstance(string mutexName = null){bool result = false;bool mutexWasCreated = false;try{bool requestInitialOwnership = true;if (mutexName == null)mutexName = currentProcess;_m = new Mutex(requestInitialOwnership, mutexName, out mutexWasCreated);if (!mutexWasCreated){result = true;}}catch (Exception ex){MessageBox.Show(ex.Message);}return result;}/// <summary>/// 有程序运行,设置焦点/// </summary>private void Focus(){foreach (Process process in Process.GetProcesses()){try{if (process.ProcessName.ToLower() != currentProcess.ToLower())continue;IntPtr hwnd = process.MainWindowHandle;if (hwnd != IntPtr.Zero){SetForegroundWindow(hwnd);ShowWindow(hwnd, 2);}}catch (Exception ex){MessageBox.Show(ex.Message);}}}private void Application_Startup(object sender, StartupEventArgs e){if(CheckRunOneInstance()){Focus();System.Windows.Application.Current.Shutdown();return;}else{new MainWindow().Show();}}}

实例链接:

https://download.csdn.net/download/lvxingzhe3/88668552

http://www.lryc.cn/news/270694.html

相关文章:

  • 【基础】【Python网络爬虫】【1.认识爬虫】什么是爬虫,爬虫分类,爬虫可以做什么
  • 【算法与数据结构】860、LeetCode柠檬水找零
  • 「Verilog学习笔记」乘法与位运算
  • CSS与JavaScript的简单认识
  • MAC 中多显示器的设置(Parallels Desktop)
  • 迁移到云原生:如何使用微服务迁移应用程序
  • kafka 的零拷贝原理
  • 华为云Stack 8.X流量模型分析(五)
  • 学习动态规划解决不同路径、最小路径和、打家劫舍、打家劫舍iii
  • nodejs微信小程序+python+PHP特困救助供养信息管理系统-计算机毕业设计推荐
  • Vue(二):计算属性与 watch 监听器
  • 25、WEB攻防——通用漏洞SQL读写注入MYSQLMSSQLPostgreSQL
  • 【第5期】前端Vue使用Proxy+Vuex(store、mutations、actions)跨域调通本地后端接口
  • 在Visual Studio(VS)编译器中,Release和Debug区别
  • 子网划分问题(实战超详解)_主机分配地址
  • 【QT】单例模式,Q_GLOBAL_STATIC 宏的使用和使用静态成员函数,eg:{简单的日志记录器}
  • 利用小红书笔记详情API:构建高效的内容创作与运营体系
  • 【K8S 二进制部署】部署单Master Kurbernetes集群
  • vue中常见的指令
  • 单片机原理及应用:开关控制LED多种点亮模式
  • 你真的了解UVM sequence的运行机制吗
  • Bug升级记
  • 爬虫详细教程第1天
  • [Linux] MySQL数据库的备份与恢复
  • Django、Python版本升级问题大汇总
  • 2023-12-30 AIGC-LangChain介绍
  • pytorch01:概念、张量操作、线性回归与逻辑回归
  • storyBook play学习
  • Android Matrix画布Canvas旋转Rotate,Kotlin
  • 私有部署ELK,搭建自己的日志中心(三)-- Logstash的安装与使用