实现同时只允许运行一个程序实例
来源:互联网 发布:什么编程语言最难学 编辑:程序博客网 时间:2024/05/17 19:22
方法一:
/// <summary>
/// 从这里开始运行
/// </summary>
[STAThread]
static void Main()
{
Process instance = RunningInstance();
if (instance == null)
{
//没有实例在运行
WeatherApp appInstance = new WeatherApp();
appInstance.StartMainGui();
}
else
{
//已经有一个实例在运行
HandleRunningInstance(instance);
}
}
#region 确保只有一个实例
public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
//遍历与当前进程名称相同的进程列表
foreach (Process process in processes)
{
//Ignore the current process
if (process.Id != current.Id)
{
//Make sure that the process is running from the exe file.
if (Assembly.GetExecutingAssembly().Location.Replace("/", "//") == current.MainModule.FileName)
{
//Return the other process instance.
return process;
}
}
}
return null;
}
private static void HandleRunningInstance(Process instance)
{
MessageBox.Show("该应用系统已经在运行!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
ShowWindowAsync(instance.MainWindowHandle, 1); //调用api函数,正常显示窗口
SetForegroundWindow(instance.MainWindowHandle); //将窗口放置最前端。
}
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(System.IntPtr hWnd);
#endregion
方法二:
[STAThread]
static void Main(string[] args)
{
bool isFirst;
System.Threading.Mutex mutex = new System.Threading.Mutex(true, "WindowAppTest", out isFirst);
//这里的myApp是程序的标识,建议换成你的程序的物理路径,这样的话如果在一个操作系统中这个标志不会和其它程序冲突
if (!isFirst)
{
MessageBox.Show("Exist");
Environment.Exit(1);//实例已经存在,退出程序
}
else
{
Application.Run(new Form1());
}
}
- 实现同时只允许运行一个程序实例
- 实现同时只允许运行一个程序实例
- 实现同时只允许运行一个程序实例
- Wince 程序只允许同时运行一个
- 只允许程序运行一个实例
- 一个程序同时只允许一个实例存在
- 只允许运行一个实例
- 只允许运行一个实例
- 只允许一个程序运行一个实例 代码
- 只允许运行一个程序
- WINCE中只允许程序运行一个实例
- WINCE中只允许程序运行一个实例
- C#程序只允许运行一个实例的解决方案
- c++ builder 只允许程序运行一个实例
- WINCE中只允许程序运行一个实例
- .net中如何只允许运行一个程序实例
- C#程序只允许运行一个实例的解决方案
- WINCE中只允许程序运行一个实例
- [翻译]Scott Mitchell 的ASP.NET 2.0数据教程之十二:在GridView控件中使用TemplateField
- JavaScript学习笔记5
- 网站设计之模板管理
- C#的usb通讯编程
- 程序运行实例数量的控制
- 实现同时只允许运行一个程序实例
- Java 2 国际化功能
- JavaScript学习笔记6
- 在VC++实现控制程序只运行唯一一个实例
- First-- C++ 获取时间
- 马化腾:差点收购YouTube
- 向数据库插入图片
- 用正则表达式来表示中文
- VB得到指定文件夹下的文件列表