首页 > 编程语言 >基于C#的应用程序单例唯一运行的完美解决方案 - 开源研究系列文章

基于C#的应用程序单例唯一运行的完美解决方案 - 开源研究系列文章

时间:2023-08-04 11:55:33浏览次数:49  
标签:Process C# System 应用程序 process 开源 单例 using

  今次介绍一个应用程序单例唯一运行方案的代码。

  我们知道,有些应用程序在操作系统中需要单例唯一运行,因为程序多开的话会对程序运行效果有影响,最基本的例子就是打印机,只能运行一个实例。这里将笔者单例运行的代码共享出来,需要的读者请自己复用该代码到自己的项目中即可。

  1、  项目目录;

  下面是项目目录,因为是一段代码,所以给出的例子比较简单。

        

 

  2、  代码介绍;

  这里的代码挺简单的,就是获取应用程序的GUID和运行的进程进行判断,因为GUID唯一,所以更改了程序名称或者改变了目录都不会有影响;而运行进程判断是附加的方式,防止当前目录的程序运行多次。

 1 namespace ProgramInstance
 2 {
 3     using System;
 4     using System.Diagnostics;
 5     using System.Reflection;
 6     using System.Runtime.InteropServices;
 7     using System.Threading;
 8 
 9 
10     /// <summary>
11     /// 单例程序操作类
12     /// </summary>
13     internal class SingleInstance
14     {
15         /// <summary>
16         /// 程序是否运行
17         /// </summary>
18         /// <returns>true 程序已运行;false 程序未运行</returns>
19         internal static bool IsRunning(out Process process)
20         {
21             //如果判断全系统唯一,直接用下列方法;如果判断当前文件夹唯一,则将GUID判断去掉;
22             new Mutex(true, 
          new Guid(((GuidAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(),
            typeof(GuidAttribute))).Value).ToString("N"),
          out bool createdNew); 23 process = RunningInstance(); 24 return (!createdNew || (process != null)); 25 } 26 /// <summary> 27 /// 获取当前程序进程实例 28 /// </summary> 29 /// <returns>程序进程实例</returns> 30 private static Process RunningInstance() 31 { 32 Process currentProcess = Process.GetCurrentProcess(); 33 foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName)) 34 { 35 if ((process.Id != currentProcess.Id) &&
              (Assembly.GetExecutingAssembly().Location.Replace("/", @"\") == currentProcess.MainModule.FileName)) 36 { 37 return process; 38 } 39 } 40 return null; 41 } 42 } 43 }

 

 1 namespace SingleInstance
 2 {
 3     using System;
 4     using System.Diagnostics;
 5     using System.Runtime.InteropServices;
 6     using System.Windows.Forms;
 7 
 8     /// <summary>
 9     /// 程序类
10     /// </summary>
11     internal static class Program
12     {
13         [DllImport("User32.dll")]
14         private static extern bool SetForegroundWindow(IntPtr hWnd);
15         [DllImport("User32.dll")]
16         private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
17 
18         /// <summary>
19         /// 应用程序的主入口点
20         /// </summary>
21         [STAThread]
22         static void Main()
23         {
24             if (ProgramInstance.SingleInstance.IsRunning(out Process process))
25             {
26                 ShowWindowAsync(process.MainWindowHandle, 9 | 1);
27                 SetForegroundWindow(process.MainWindowHandle);
28 
29                 return;
30             }
31 
32 
33             Application.EnableVisualStyles();
34             Application.SetCompatibleTextRenderingDefault(false);
35 
36             Application.Run(new Form1());
37         }
38     }
39 }

  3、  运行截图;

  因为是代码段复用,所以这里不提供运行截图了。

 

  4、  源码下载;

  需要该例子代码的,请移步到下面链接进行下载:

  https://download.csdn.net/download/lzhdim/88158095

 

  上面介绍了C#编写的应用程序单例运行的例子,希望对有该需求的读者以帮助。后面会将笔者认为有用的代码段共享出来,让需要的读者进行代码段复用。

 

  注:如果需要应用程序多开(放到其它文件夹中,或者在当前文件夹中复制更改应用程序名称),请将GUID的判断去掉即可。

标签:Process,C#,System,应用程序,process,开源,单例,using
From: https://www.cnblogs.com/lzhdim/p/17603873.html

相关文章

  • 个人笔记,关于css样式
    /*引入样式<linkhref="https://fonts.font.im/css?family=Open+Sans"rel="stylesheet"type="text/css">*/html{/*px表示“像素(pixels)”:基础字号为10像素*/font-size:20px;/*Googlefonts输出的CSS*/font-family:'Op......
  • CentOS7 安装部署 OceanBase 数据库
    OceanBase是由蚂蚁集团完全自主研发的国产原生分布式数据库,本文以x86架构的CentOSLinux7.9主机作为环境对该数据库的安装部署进行介绍。背景OceanBase数据库自V4.0.0开始提供统一的安装包all-in-onepackage。您可以通过这个统一的安装包一次性完成OBD、OceanBase......
  • 如何用Confusion matrix,classification report,ROC curve (AUC)分析一个二分类问题
    ROChttps://zhuanlan.zhihu.com/p/246444894   Sure,let'screatearandomconfusionmatrixasanexample,andthenI'llexplainwhateachelementinthematrixmeans:Supposewehaveabinaryclassificationproblem,wherethetruelabelsareas......
  • 《介绍篇》c#为什么能在桌面应用上战胜java
    参考链接:https://blog.csdn.net/weixin_39539761/article/details/114158817参考链接:http://it.cha138.com/shida/show-5705680.htmljava语言确实是一种比较不错的语言。相比于C,C++等语言来说,java是移植性和语言的形式上都是非常优秀,尤其是Web开发和Android移动应用开发方面,可以......
  • Codeforces Round 424 (Div. 1)D. Singer House
    传送门显然要自底向上进行\(dp\)深度相同的子树结构相同所以可以利用深度来代表子树。那么就应该统计出有向路径的个数。考虑路径由链所拼成。那么状态里应该有有向链的条数。设\(f_{i,j}\)表示深度为\(i\)链条数为\(j\)的方案数。不选当前的节点则\(f_{i,j}=f_{i+1,k}\cdot......
  • uniapp 使用camera组件IOS圆角不生效问题
    <viewclass="cameraViewgui-margin-top"><cameraclass="camera-box"device-position="front"flash="off"></camera></view>.cameraView{width:600rpx;height:600rpx;border-radius:50%;bord......
  • 《介绍篇》c#的起源
    c#的起源参考链接:https://blog.csdn.net/Heibai_yuheibai/article/details/119738666c++出现1975年微软公司成立,刚开始它并不是做操作系统的,而是做PC编程软件的,我们熟知的BASIC,就是比尔盖茨把它移植到了PC上。记得80年那会小霸王学习机上还有BASIC。1980年,IBM选择微软为其编写......
  • Java面试题 P59:微服务篇:分布式系统理论-CAP和BASE
           ......
  • python 操作oracle
    表DDL--"C##TAPDATA_TEST".ALAM3definitionCREATETABLE"C##TAPDATA_TEST"."ALAM3"( "UID1"VARCHAR2(100)NOTNULLENABLE, "UID2"VARCHAR2(100)NOTNULLENABLE, "COLUMN1"VARCHAR2(100),......
  • 数据格式的处理 echarts数据改为 Table表格格式的数据
      前景后端返回的echarts展示数据格式,既要展示echarts又要展示table表格,echarts的数据格式为下面{xData:['Mon','Tue','Wed','Thu','Fri','Sat','Sun'],yData1:[10,52,200,334,390,330,220],yData2:......