熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Delphi編程 >> 正文

delphi中,讓程序只運行一次的方法[2]

2022-06-13   來源: Delphi編程 

  program MyThreadTest;
  uses
   Windows
   Forms
   SysUtils
   Messages
   Dialogs
    Unit in Unitpas {Form}
  {$R *res}
  var
   myMutex
   FindHid: HWND;
   MoudleName: string;
  function EnumWndProc(hwnd: Thandle; param: Cardinal): bool; stdcall;
  //由於用於api回調函數請使用windows傳統的參數傳遞方式stdcall
  var
    ClassName WinMoudleName: string;
    WinInstance: THandle;
  begin
    result := true;
    SetLength(ClassName );
    GetClassName(hwnd pchar(ClassName) length(ClassName)); //獲得當前遍歷窗口的類名
    ClassName := pchar(ClassName); //在字符串後加結束符確定字符串結束
    if UpperCase(ClassName) = UpperCase(TFormClassName) then //比較類名
   begin
      WinInstance := GetWindowLong(hwnd GWL_HINSTANCE); //獲得當前遍歷窗口的實例
    setlength(WinMoudleName );
    //獲得當前遍歷窗口的程序文件名
    GetModuleFileName(WinInstance pchar(WinMoudleName) length(WinMoudleName));
    WinMoudleName := pchar(WinMoudleName);
    WinMoudleName :=ExtractFileName(WinMoudleName);
    //MoudleName為工程全局變量自身程序的文件名
    if UpperCase(WinMoudleName) = UpperCase(MoudleName) then
    begin
        FindHid := hwnd;//FindHid為工程全局變量保存找到的句炳
     result := false; //找到以後就結束遍歷
      end;
    end;
  end;
  begin
   // CreateMutex建立互斥對象並且給互斥對象起一個唯一的名字
    myMutex := CreateMutex(nil false hkOneCopy);
   if WaitForSingleObject(myMutex ) <> wait_TimeOut then
  //程序沒有被運行過
    begin
      ApplicationInitialize;
      ApplicationCreateForm(TForm Form);
    ApplicationRun;
   end else
   begin
    SetLength(MoudleName );
    //獲得自己程序文件名
    GetModuleFileName(HInstance pchar(MoudleName) length(MoudleName));
    MoudleName := pchar(MoudleName);
    MoudleName := ExtractFileName(MoudleName);
    EnumWindows(@EnumWndProc ); //調用枚舉函數
    if FindHid <> then
    begin
     ShowWindow(FindHidSW_RESTORE);
     SetForegroundWindow(FindHid);
    end;
   end;
  end
  [EnumWindows函數使用]
  EnumWindows 用來列舉屏幕上所有頂層窗口
  MSDN
  The EnumWindows function enumerates all toplevel windows on the screen by passing the handle to each window

[]  []  []  


From:http://tw.wingwit.com/Article/program/Delphi/201311/24833.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.