内容简介:[Winform]检测exe是否已经运行,并将其置顶
摘要
在很多pc应用中,基本上都需要有这样的判断,保证在一个终端只运行一个winform的client。并且如果最小化了,用户再次双击桌面图标的时候,将client置顶显示。
解决方案
需要使用windows的API,可以很方便的实现这个目的。
代码如下:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
class AppMain
{
[DllImport("user32.dll")] private static extern
bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")] private static extern
bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")] private static extern
bool IsIconic(IntPtr hWnd);
private const int SW_HIDE = 0;
private const int SW_SHOWNORMAL = 1;
private const int SW_SHOWMINIMIZED = 2;
private const int SW_SHOWMAXIMIZED = 3;
private const int SW_SHOWNOACTIVATE = 4;
private const int SW_RESTORE = 9;
private const int SW_SHOWDEFAULT = 10;
static void Main()
{
// get the name of our process
string proc=Process.GetCurrentProcess().ProcessName;
// get the list of all processes by that name
Process[] processes=Process.GetProcessesByName(proc);
// if there is more than one process...
if (processes.Length > 1)
{
// Assume there is our process, which we will terminate,
// and the other process, which we want to bring to the
// foreground. This assumes there are only two processes
// in the processes array, and we need to find out which
// one is NOT us.
// get our process
Process p=Process.GetCurrentProcess();
int n=0; // assume the other process is at index 0
// if this process id is OUR process ID...
if (processes[0].Id==p.Id)
{
// then the other process is at index 1
n=1;
}
// get the window handle
IntPtr hWnd=processes[n].MainWindowHandle;
// if iconic, we need to restore the window
if (IsIconic(hWnd))
{
ShowWindowAsync(hWnd, SW_RESTORE);
}
// bring it to the foreground
SetForegroundWindow(hWnd);
// exit our process
return;
}
// ... continue with your application initialization here.
}
}
上面代码的意思是判断exe是否已经在进程列表中,如果存在则标识已经运行了客户端,如果存在获取窗口的句柄,并进行展示。
资料来源
https://www.codeproject.com/Articles/2976/Detect-if-another-process-is-running-and-bring-it
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- PHP 运行时漏洞检测
- Ubuntu,JavaFX,Java运行时环境已经检测到一个致命的错误
- 手机端运行卷积神经网络的一次实践 -- 基于 TensorFlow 和 OpenCV 实现文档检测功能
- springboot服务优雅关机脚本(在停止服务的命令发出后将执行完正在运行的进程)外加检测进程死掉自...
- 恶意软件如何绕过AMSI检测以逃避检测
- 行人检测新思路:高级语义特征检测取得精度新突破
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
亿级流量网站架构核心技术
张开涛 / 电子工业出版社 / 2017-4 / 99
《亿级流量网站架构核心技术》一书总结并梳理了亿级流量网站高可用和高并发原则,通过实例详细介绍了如何落地这些原则。本书分为四部分:概述、高可用原则、高并发原则、案例实战。从负载均衡、限流、降级、隔离、超时与重试、回滚机制、压测与预案、缓存、池化、异步化、扩容、队列等多方面详细介绍了亿级流量网站的架构核心技术,让读者看后能快速运用到实践项目中。 不管是软件开发人员,还是运维人员,通过阅读《亿级流......一起来看看 《亿级流量网站架构核心技术》 这本书的介绍吧!