您的位置:首页 > 编程语言 > C#

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());
}

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: