我的winform程序打开后,再点击应用程序图标,会又打开一个。
如何控制让我写的winform程序只能打开一个呢? 都有那些方法??
如何控制让我写的winform程序只能打开一个呢? 都有那些方法??
解决方案 »
- 新人菜鸟求教如何对excel数据导入到C#dataview
- 跪求!C# 查询XML文件数据库算法。
- 求c# combox 国家省份城市 三级联动 源码
- 无法添加项目引用
- 求助:一直用vb.net+sql server做开发,~如果转c#难吗?多长时间达到vb.net相应水平?
- WEB调用CS客户端(浏览器插件) 新人求教
- 关于用c#做的记事本的一些问题!!!!!!!!!!!!!!!!!!!!
- 关于listbox查询问题
- 100分求解滚动条的问题(分在别的帖子上)
- 我在C#下运行 .Net Petshop 总是弹出“文件保存”对话框
- 使用 XmlSerializer 序列化对象后,我想给序列化后的 XML 文件中添加一段注释??怎么在序列化过程让它自动添加呢???
- 一个sql查询问题,大家帮帮忙,没分了
http://tag.csdn.net/Article/4216c4ee-f501-474c-a7d9-6023cecf7f3c.html
里。这个文件包含 Main
入口函数,是整个程序的入口。 定义一个静态互斥体:static Mutex InstanceMutex
定义一个静态判断方法。用来判断这个互斥体是否已在系统中存在:
static bool DoesAnInstanceRunning() {
try {
Mutex.OpenExisting("SPS");
}
catch (Exception) {
return false;
}
return true;
}
在 Main 函数中判断是否有实例已经运行,如果没有,则运行:
[STAThread]
static void Main() {
if (DoesAnInstanceRunning()) return;
InstanceMutex = new Mutex(true, "SPS"); Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Applicaion.Run(new Form1());
简单一点的方法是检测进程是否开启
//帮助
Process[] ps=Process.GetProcessesByName("yourApp.exe");
if(ps.Length==0&&File.Exists("yourApp.exe"))
Process.Start("yourApp.exe");yourApp.exe是你的项目的进程名称,最好运行一下然后任务管理器确认是什么名称
static void Main()
{
Process instance = RunningInstance();
if (instance == null)
{
Application.Run(new Initial());
}
}
public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName); //Loop through the running processes in with the same name
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;
}
}
}
//No other instance was found, return null.
return null;
}
提供的是2005中的方法把?可惜我没用过。如果是2003:
Process.GetProcessesByName
这个方法是有局限的,如果程序要求严谨,最好别用。
调api吧。 codeproject上有用例。
或者在Main函数中:
using System.Reflection;
..
bool isCreatedNew;
System.Threading.Mutex myMutex = new System.Threading.Mutex(true,"MY*(((*())(*",out isCreatedNew);
if(!isCreatedNew)
{
MessageBox.Show("Only one instance can run at the same time.", "AAAAAAA");
return;
}
...do what you want.
http://blog.csdn.net/zhzuo/archive/2006/06/30/857405.aspx
http://blog.csdn.net/zhzuo/archive/2006/07/04/874745.aspx