c#检查程序是否已经运行,如何防止多次运行同一个程序?
2014-03-13 11:16
746 查看
using System; using System.Collections.Generic; using System.Windows.Forms; using System.ServiceProcess; using System.Runtime.InteropServices; using System.Diagnostics; namespace ReplaceNamespace { static class Program { #region win32函数 [DllImport("user32.dll")] public static extern IntPtr FindWindow(string lpSpecifiedClassName, string lpWindowName); [DllImport("user32.dll ", SetLastError = true)] public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab); [DllImport("user32.dll", EntryPoint = "ShowWindow", CharSet = CharSet.Auto)] public static extern int ShowWindow(IntPtr hwnd, int nCmdShow); public const int SW_RESTORE = 9; public static IntPtr formhwnd; #endregion /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Process currentproc = Process.GetCurrentProcess(); Process[] processcollection = Process.GetProcessesByName(currentproc.ProcessName.Replace(".vshost", string.Empty)); if (processcollection.Length > 1) //程序已经运行 { foreach (Process process in processcollection) { if (process.Id != currentproc.Id) { // 句柄等于0,说明窗体已隐藏 if (process.MainWindowHandle.ToInt32() == 0) { // 获得窗体句柄 formhwnd = FindWindow(null, "窗体的标题文本"); // 显示并切换到窗体 ShowWindow(formhwnd, SW_RESTORE); SwitchToThisWindow(formhwnd, true); } else { SwitchToThisWindow(process.MainWindowHandle, true); } } } } else { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } } }
相关文章推荐
- 发布订阅者模式之C#委托实现
- c#显示隐藏的窗体和托盘中的程序
- C#委托的异步调用
- C#页面前台绑定数据 <%%><%#%><%=%>
- C#- 控制台Timer
- C#.NET 大型通用信息化系统集成快速开发平台 4.1 版本 - 即时消息提醒功能改进
- C# 对 list<T>中的数据按某字段的大小进行排序
- C#的时间转换小记
- 有关c#装箱和拆箱知识整理
- 【C#基础学习】学习日记2
- 第二章:核心C#
- C# 与 VC Dll 传输信息
- C#中的yield关键字
- C#中的迭代器基础
- Using C# Yield for Readability and Performance
- C#中使用正则表达式验证电话号码、手机号、身份证号、数字和邮编
- c#中char.IsDigit和char.IsNumeric的区别
- C# 调用WebService的方法
- C#动态调用webservice
- C#创建windows服务图解