原文地址 :http://www.cnblogs.com/emanlee/archive/2009/08/31/1557379.html

    using System;
using System.Threading;
using System.Collections.Generic;
using System.Windows.Forms; namespace ArresterSerialPort
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{ Boolean createdNew; //返回是否赋予了使用线程的互斥体初始所属权
System.Threading.Mutex instance = new System.Threading.Mutex(true, "ArresterSerialPort", out createdNew); //同步基元变量
if (createdNew) //赋予了线程初始所属权,也就是首次使用互斥体
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
instance.ReleaseMutex();
}
else
{
MessageBox.Show("已经启动了一个程序,请先退出", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
} //Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new ArresterMainForm());
}
}
}
防止程序运行多个实例的方法有多种,如:通过使用互斥量和进程名等.
而我想要实现的是:在程序运行多个实例时激活的是第一个实例,使其获得焦点,并在前端显示. 主要调用两个API函数:
#region API函数
/// <summary>
/// 该函数设置由不同线程产生的窗口的显示状态。
/// </summary>
/// <param name="hWnd">窗口句柄</param>
/// <param name="cmdShow">指定窗口如何显示。查看允许值列表,请查阅ShowWlndow函数的说明部分。</param>
/// <returns>如果函数原来可见,返回值为非零;如果函数原来被隐藏,返回值为零。</returns>
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
/// <summary>
/// 该函数将创建指定窗口的线程设置到前台,并且激活该窗口。键盘输入转向该窗口,并为用户改各种可视的记号。
// 系统给创建前台窗口的线程分配的权限稍高于其他线程。
/// </summary>
/// <param name="hWnd">将被激活并被调入前台的窗口句柄。</param>
/// <returns>如果窗口设入了前台,返回值为非零;如果窗口未被设入前台,返回值为零。</returns>
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
private const int SW_HIDE = ; //隐藏
private const int SW_SHOWNORMAL = ; //Normal
private const int SW_SHOWMINIMIZED = ; //最小化
private const int SW_SHOWMAXIMIZED = ; //最大化
private const int SW_SHOWNOACTIVATE = ; //激活
private const int SW_RESTORE = ; //Restore
private const int SW_SHOWDEFAULT = ; //Default
#endregion #region 封装API函数
private static void HandleRunningInstance(Process instance)
{
// 确保窗口没有被最小化或最大化
ShowWindowAsync(instance.MainWindowHandle, SW_SHOWNOACTIVATE);
// 设置真实例程为foreground window
SetForegroundWindow(instance.MainWindowHandle);// 放到最前端
}
private static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
foreach (Process process in processes)
{
if (process.Id != current.Id)
{
// 确保例程从EXE文件运行
if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
{
return process;
}
}
}
return null;
}
#endregion 以下是在Program.cs类如何调用:
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
try
{
Process instance = RunningInstance();
if (instance == null)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm);
}
else
{
HandleRunningInstance(instance);
}
catch(Exception e){}
}

(转)C#.NET WINFORM应用程序中控制应用程序只启动一次的更多相关文章

  1. c# WinForm窗体编程中对窗体程序设置快捷键

    c# WinForm窗体编程中对窗体程序设置快捷键http://www.cnblogs.com/bison1989/archive/2011/09/19/2180977.html /// <su ...

  2. java程序怎么在一个电脑上只启动一次,只开一个进程

    目录 <linux文件锁flock> <NIO文件锁FileLock> <java程序怎么在一个电脑上只启动一次,只开一个进程> 方案1: 单进程程序可以用端口绑定 ...

  3. 在 DotNetCore 3.0 程序中使用通用协议方式启动文件关联应用

    问题描述 在传统的基于 .NET Framework 的 WPF 程序中,我们可以使用如下代码段启动相关的默认应用: # 启动默认文本编辑器打开 helloworld.txt Process.Star ...

  4. ABAP 在被访问的程序中获取访问程序的全局变量

    前些日子接到过一个看起来比较普通的需求: 存在一个系统标准函数组FG01,内含函数模块FM00,FM01……等等.在系统程序中,FM00会调用FM01,通过FM01获取获取某些数据. 需求要求,复制一 ...

  5. C# 在程序中控制IIS服务或应用程序池关闭重启

    //停止IIS服务 ServiceController sc = new ServiceController("iisadmin"); if(sc.Status=ServiceCo ...

  6. ASP.NET C# 如何在程序中控制IIS服务或应用程序池重启?

    停止IIS服务ServiceController sc = new ServiceController("iisadmin");if(sc.Status==ServiceContr ...

  7. qt 程序中执行额外程序和脚本

    1.最简单的,我们可以通过system直接启动一个应用程序或者脚本:(但是要调用 #include <stdlib.h>) system("./helloworld") ...

  8. .Net中把图片等文件放入DLL中,并在程序中引用

    原文:.Net中把图片等文件放入DLL中,并在程序中引用 [摘要] 有时我们需要隐藏程序中的一些资源,比如游戏,过关后才能看到图片,那么图片就必须隐藏起来,否则不用玩这个游戏就可以看到你的图片了,呵呵 ...

  9. c#控制WPF程序自动登录(Automation方式实现)

    说明:winForm窗体,可以通过win32接口dll的findWindow之类的函数来实现查找winform窗口,mfc窗口等. 但是wpf却是不实用这些,可以靠automation方式来进行操作. ...

随机推荐

  1. node ->rman to RAC (迁移)

    版权声明:本文为博主原创文章.未经博主同意不得转载. https://blog.csdn.net/lmocm/article/details/34435699 *.audit_file_dest='/ ...

  2. dockerfile创建php容器(安装memcached、redis、gd、xdebug扩展)

    dockerfile创建php容器(含有memcached.redis.gd.xdebug扩展) 代码如下: FROM php:7.2-fpm COPY redis-3.1.6.tgz /home/r ...

  3. java-jdbc数据库连接

    web.xml:(web.xml) <!-- 加载spring容器 --> <context-param> <param-name>contextConfigLoc ...

  4. Spring整合Hibernate(转)

    概述 Spring整合Hibernate有什么好处? 1.由IOC容器来管理Hibernate的SessionFactory 2.让Hibernate使用上Spring的声明式事务 整合步骤 整合前准 ...

  5. Git-git rebase详解

    git合并代码方式主要有两种方式,分别为:1.merge处理,这是大家比较能理解的方式.2.rebase处理,中文此处翻译为衍合过程. git rebase操作讲解例子: cd /usr/local/ ...

  6. inf 启动

    How to install an INF file using Delphi If you need to install an "inf" file using Delphi, ...

  7. elasticsearch mysql logstash 同步 简单配置【环境centos7 elasticsearch 6.0 mysql 5.7 logstash 6.0】

    插件:logstash-input-jdbc 安装插件logstash-input-jdbc 1.安装 gem   yum install gem 2.替换国内的镜像   gem sources -- ...

  8. Windows Remote Shell(WinRM)使用介绍

    最近,为了实验我们安装了台Windows Server Core的服务器,没有图形界面的系统总会给人一种很完全的感觉,我们本着安全到底的想法,使用了Windows Remote Shell 的管理方式 ...

  9. PL/SQL Developer 使用小技巧

    1.PL/SQL Developer记住登陆密码 在使用PL/SQL Developer时,为了工作方便希望PL/SQL Developer记住登录Oracle的用户名和密码: 设置方法:tools- ...

  10. IO练习文件读取

    import java.io.*; public class CheckFile { private File f ; private BufferedReader bdr; private char ...