日期:2014-05-19  浏览次数:20725 次

请教:如何控制自己写的win程序只可运行一个实例 ? 谢谢.
RT

------解决方案--------------------
定义一个静态int i=0,运行第一次+1;判断是否为1,是1就不运行,关闭时候记-1;
------解决方案--------------------
以前记得在项目的属性中可以设置

------解决方案--------------------
在你的代码的main函数的最前边加这样一段试试:
bool startupMutex = true;
Mutex UOPTmutex =new Mutex( true, "UOPTmutex ", out startupMutex );
if (!startupMutex )
{
return;
}
------解决方案--------------------
看看用进程来限制只运行一个实例的方法

/// <summary>
/// 應用程式的主要進入點。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Process inst = RunningInstance();

if (inst == null)
{
Application.Run(new EIPNotify());
}
}
public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);

foreach (Process process in processes)
{
if (process.ProcessName == current.ProcessName && process.Id != current.Id)
{
return process;
}
}
return null;
}
------解决方案--------------------
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;

namespace PractiseSystem
{
static class Program
{
[DllImport( "User32.dll ")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
[DllImport( "User32.dll ")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
private const int WS_SHOWNORMAL = 1;

/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Process instance = RunningInstance();
if (instance == null)
{
Application.Run(new Form1());

}
else
{
HandleRunningInstance(instance);
}
}

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.