Let the program only run an instance (Delphi)

xiaoxiao2021-03-06  20

Let the program only run an instance (Delphi) Windows Next typical feature is multitasking, we can open multiple windows at the same time, or run multiple instances of the program at the same time, such as the multi-resource manager for file Mobile replication operation. But sometimes for some kind of consideration (such as security), we have to make some restrictions, allowing the program to only run an instance. In Delphi programming, the author summarizes the following methods: 1. Find window law This is the most simple method. Use the FINDWINDOW function to find the window with the same window name and title before the program is run. If it is found, there is already an instance already existing. Add the following code to the initialization section of the project source file: Program OneApp Uses Forms, Windows; (Several methods described here) The Windows unit is required to add a Windows unit in the project source file, and will not be repeated later) VAR HWnd: Thandle; Begin Hwnd: = FindWindow ('TForm1', 'SingleApp'); if hwnd = 0 Then Begin Application.initialize; Application.createform (TFORM1, FORM1); Application.Run; end; end; findwindow () function with two parameters, where A parameter can be ignored, but the author strongly recommends that both parameters are used, and the programs are not allowed to use the same class name, they will not be correct. Also, if you run the program in the Delphi IDE window, you can't run once, because there is already the same name and title window: Forms when designing. Second, using a mutex object If you feel that the method of finding the window is not too high, you can use the method of creating a mutex. Although mutex is usually used for synchronous connections, it is also very convenient to use this place. It is easy to get it in just 4 codes. ***************************************************** VAR MUTEX: THANDE ; begin Mutex: = CreateMutex (nil, True, 'SingleApp'); if GetLastError <> ERROR_ALREADY_EXISTS then // begin Application.Initialize another example, if absent; Application.CreateForm (TForm1, Form1); Application.Run; end; ReleaseMutex (Mutex); End. ************************************************************ **** Third, the global atomic law can also use the method of adding global atoms to the system to prevent the operation of multiple program instances. The global atom is responsible for maintenance by the Windows system, which guarantees that each of which is unique, manages its reference count, and cleared from memory when the reference count of the global atom is 0. We add a string within 255 bytes with the globalAdDatom function to the global atom, check whether the global atom has existed with GlobalFindatom, and finally deletes the added global atom with the GlobalDeleTom function at the end of the program.

转载请注明原文地址:https://www.9cbs.com/read-40218.html

New Post(0)