使用互斥对象让程序只运行一次

以下是用delphi的一个空project做的测试(完整的代码):

program Project1;

uses
    Windows,    ///该unit一定要包含,系统用到了windows api
    Forms,
    Unit1 in 'Unit1.pas' {Form1};

var
    myMutex,hMutex,FindHid:HWND;
    MoudleName:string;

function EnumWndProc(hwnd:Thandle;param:Cardinal):boolean;stdcall;
//由于用于api回调函数,请使用windows传统的参数传递方式stdcall
var
    ClassName,WinMoudleName:string;
    WinInstance:THandle;
begin
    result:=true;
    SetLength(ClassName,100);
    GetClassName(hwnd,pchar(ClassName),length(ClassName));//获得当前遍历窗口的类名
    ClassName:=pchar(ClassName);//在字符串后加结束符,确定字符串结束
    if ClassName=TForm1.ClassName then//比较
    begin
        WinInstance:=GetWindowLong(hwnd,GWL_HINSTANCE);//获得当前遍历窗口的实例
        setlength(WinMoudleName,100);
        GetModuleFileName(WinInstance,pchar(WinMoudleName),length(WinMoudleName));
        //获得当前遍历窗口的程序文件名
        WinMoudleName:=pchar(WinMoudleName);
        if WinMoudleName=MoudleName then//MoudleName为工程全局变量,自身程序的文件名
        begin
            FindHid:=hwnd;//FindHid为工程全局变量保存找到的句炳
            result:=false;//找到以后就结束遍历
        end;
    end;
end;

{$R *.res}


begin
    hMutex:=CreateMutex(nil,false,'Project1');
    if WaitForSingleObject(hMutex,0)<>wait_TimeOut then
    begin
        myMutex:=CreateMutex(nil,false,'Project1');// CreateMutex建立互斥对象,并且给互斥对象起一个唯一的名字。
        if WaitForSingleObject(myMutex,0)<>wait_TimeOut then//程序没有被运行过
        begin
            Application.Initialize;
            Application.CreateForm(TForm1, Form1);
            Application.Run;
        End;
    end
    else
    begin
        SetLength(MoudleName,100);
        GetModuleFileName(HInstance,pchar(MoudleName),length(MoudleName));
        //获得自己程序文件名
        MoudleName:=pchar(MoudleName);
        EnumWindows(@EnumWndProc,0);//调用枚举函数
        if FindHid<>0 then
            SetForegroundWindow(FindHid);
    end;
end.

可参考: http://www.7880.com/Info/Article-215ddec0.html

                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值