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

c# 控制职能运行单一实例,再次运行显示已经运行的实例

2014-12-22 14:05 267 查看
有这么个需求,软件只能运行一个实例,软件运行后可以让其隐藏运行

再次运行这个软件的时候就让正在运行的实例显示出来

=================================

当软件隐藏后没办法拿到句柄

于是只有第一次运行的时候讲句柄保存下来,于是有了下面的

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO;

namespace NIKE.Client
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
//StaticPass.cf = new ClientForm();
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new FormMain());
bool ret;
System.Threading.Mutex mutex = new System.Threading.Mutex(true, Application.ProductName, out ret);
if (ret)
{
System.Windows.Forms.Application.EnableVisualStyles();   //这两行实现   XP   可视风格
//System.Windows.Forms.Application.DoEvents();             //这两行实现   XP   可视风格
Application.SetCompatibleTextRenderingDefault(false);
System.Windows.Forms.Application.Run(new FormMain());
//   Main   为你程序的主窗体,如果是控制台程序不用这句
mutex.ReleaseMutex();
}
else
{

string path = Application.StartupPath + "\\Handle";
int handle = 0;
using (StreamReader reader = new StreamReader(path))
{
handle = int.Parse(reader.ReadToEnd());
}
IntPtr i = new IntPtr(handle);
bool isok = ShowWindow(i, 1);
SetForegroundWindow(i);
//  SetForegroundWindow(hWnd);
// MessageBox.Show(null, "有一个和本程序相同的应用程序已经在运行,请不要同时运行多个本程序。\n\n本次打开无效", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
//   提示信息,可以删除。
Application.Exit();//退出程序
}
}

[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_SHOWNORMAL = 1;

}
}


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