凯发真人娱乐

基于c#的应用程序单例唯一运行的完美凯发真人娱乐的解决方案 -凯发真人娱乐

2023-10-19,,

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

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

  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 ///
11 /// 单例程序操作类
12 ///

13 internal class singleinstance
14 {
15 ///
16 /// 程序是否运行
17 ///

18 /// true 程序已运行;false 程序未运行
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 ///
27 /// 获取当前程序进程实例
28 ///

29 /// 程序进程实例
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 ///
9 /// 程序类
10 ///

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 ///
19 /// 应用程序的主入口点
20 ///

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的判断去掉即可。

基于c#的应用程序单例唯一运行的完美 - 研究系列文章的相关教程结束。

网站地图