Go In Delphi, a method that lets the program run only once

Source: Internet
Author: User

Program Onlyrunone;uses forms,windows,sysutils, Dialogs, Unit1 in ' Unit1.pas ' {Form1};     {$R *.res}varmymutex:hwnd;beginmymutex:=createmutex (nil,false, ' 11111 '); The name can only be system-wide.  If WaitForSingleObject (mymutex,0) <>wait_timeout thenbegin application.initialize;  Application.createform (TForm1, Form1);  Application.Run;          End ELSE begin Application.messagebox (' There is already a case running, this case cannot run ', ' hint ', mb_ok+mb_iconinformation);  Application.terminate; End;end.         Hmutex:=createmutex (nil,true, ' test1 '); If Getlasterror=error_already_exists then begin Application.messagebox (' There is already a case running, this case cannot run ', ' hint ', m             B_ok+mb_iconinformation);             Application.terminate;         Abort; End Where Test1 is a random character, but if other programs also use the name, the 2 programs can only find a oh. Online to find a lot of methods, a lot of loopholes in their own summary of the experiment came out below is the correct program Project1; Uses Forms,windows,sysutils,dialogs, Unit1 in ' Unit1.pas ' {Form1}, Unit2 in ' Unit2.pas ' {Form2}, Unit3 in ' UNIT3.P As ' {FORM3}; {$R *.res} var Mymutex:hwnd; Begin MYmutex:=createmutex (Nil,false, ' hkonecopy '); If WaitForSingleObject (mymutex,0) <>wait_timeout then begin application.initialize; Application.createform (TForm1, Form1); Application.createform (TForm2, Form2); Application.createform (TFORM3, FORM3); Application.Run; End ELSE begin ShowMessage (' You have already run the program at the bottom right corner of the screen '); End    End. Multi-instance refers to having multiple copies of the same application running at the same time. Multiple copies of the same application can run independently of each other and are a feature provided by the WIN32 operating system. But sometimes, we may want the user to start the application and no longer start another copy of it. For example, a Device resource control program, like a modem and a parallel port.  In this case, it is necessary to use program code to prevent simultaneous copies of multiple programs from running. In 16-bit Windows, it is easy to prevent multiple instances from appearing because the system variable Hprevinst can be used to determine if there are other instances.  When the Hprevinst variable is not 0 o'clock, it means that there is already another instance of the application running. However, there are R32 insulating layers between each process in the WIN32 system to isolate each other. Therefore, the value of the variable Hprevinst in the WIN32 system is always 0.  Another technique that fits both the WIN32 system and the 16-bit Windows is to call the FindWindow () API function to search for an activated program window. The Windows API provides the function FindWindow, which can be the application at startup to check if it already exists.   The syntax of this function in Delphi is: function FindWindow (Lpclassname:pchar, Lpwindowname:pchar): HWND; Where the parameter lpcalssname is the name of the class of the window to find, and the parameter lpwindowname is the title of the window to find (Caption). If the corresponding window instance is found, the integer value of the window handle that is not 0 is returned, otherwise 0 is returned. As a result, it is possible to determine whether the application's main window (or a window that exists with the application) existsThere are already instances.      For example: H: = FindWindow (' TForm1 ', nil); If H = 0 THEN BEGIN ShowMessage (' did not find the same application instance.       ‘); Add the statement that loads the application//end ELSE begin ShowMessage (' Application already loaded.       ‘);      SetActiveWindow (H); End, where the position of the parameter lpwindowname is replaced with the Delphi reserved word nil, because the title of the window may change in the application.  The Windows API function SetActiveWindow is used to specify the active window. However, this approach has two drawbacks: one is that it can only search Windows based on the window class name or title, but the window is likely to be duplicated throughout the system. Therefore, it is unreliable to do so. The method of using the title of the window also has a problem, because the title of the window may change (in the case of Delphi and Word, each time you open a different file, their title will change), so this method is not advisable.  Another drawback is that it iterates through all the windows each time it is searched, so that execution comes in very slowly. Therefore, the best solution in the WIN32 system is to take advantage of those API objects that are not dependent on the process, and their use is simple, and the mutex can solve the problem. When an application runs for the first time, we make a mutex object created by the API function CreateMutex (). The parameter lpname of this function is a string that uniquely identifies the mutex object. When an instance of an application is to be run, it first uses OpenMutex () to open the mutex object and returns a non-0 value if there is already a mutex created by CreateMutex ().  Also, when you try to run another instance of a program, the first instance is activated. The best solution for this problem is to register a message with the RegisterWindowMessage () function and create a unique message identifier in the application at the first run.    Then, the first instance responds to the message so that it is activated by a second instance. This method prevents new instances from being produced, but is not advanced, but is simpler.     Program Live in Project program file;     Uses Windows, Forms, Shellapi, Sysutils,..; {$R *. TLB} {$R *.res} var    Hmutex:hwnd;   Ret:integer;     Begin Application.initialize;     Atitle: = ' liveauction ';       Application.title: = ' liveauction ';  Hmutex:=createmutex (Nil,false,pchar (atitle));     Establish mutually exclusive object, the name is atitle--' liveauction ' ret:=getlasterror;  If ret<>error_already_exists THEN BEGIN//Do what we normally should do end else ReleaseMutex (Hmutex);   Prevents the creation of multiple program instances Application.Run;  End.  Check if an EXE file is running function exe_is_running (const exename:string): Boolean;     EXEName: Do not extend the EXE main file name Var Hcurrentwindow:hwnd;   SZTEXT:ARRAY[0..254] of Char;     Begin Result: = False;     Hcurrentwindow:=getwindow (Application.handle,gw_hwndfirst);         While Hcurrentwindow <> 0 does begin if GetWindowText (Hcurrentwindow, @sztext, 255) >0 then BEGIN            If lowercase (pchar (@sztext)) =lowercase (exename) THEN BEGIN Result: = true;          Exit;       End       End     Hcurrentwindow:=getwindow (Hcurrentwindow,gw_hwndnext);   End End;Method: If we want to determine if the ' Live.exe ' program is running/has started if exe_is_running (Live) then ... else .... 

[Go to]delphi, let the program run only once

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.