The program only runs an instance and activates the previous instance

xiaoxiao2021-03-06  42

The program runs only one instance, an example of the former and activate Author: Geng sea by

Download This example engineering (download to the VC Knowledge Library link) Implementing the program only has a lot of ways, but the principle is the same, that is, set a tag for the first time, check the tag every time, if there is The explanation has been run. Specific implementation: 1. When the program is initialized (InitInstance ()) enumerates all the windows, find if the instance of this program exists 2, add a tag to the properties list of this window when the main window is initialized so that the program lookup Some key code 1, enumerate all windows in the use of the app, find this program instance

HWND OLDHWND = NULL;

Enumwindows (EnumWndProc, (LPARAM) & OldhWnd); // Enumerate all running windows

IF (OldhWnd! = NULL)

{

AfxMessageBox ("This program is already running");

:: ShowWindow (OldhWnd, SW_SHOWNORMAL); // Activate the previous program found

:: setForegroundWindow (OldhWnd); // Set it to the foreground window

Return false; // Exit this operation

} 2, add the enumWndProc window process function:

// Added Identification only runs once attribute name

CString g_szpropName = "Your prop name"; // ourselves define a property name

Handle g_hvalue = (handle) 1; // Define a property value

Bool Callback EnumWndProc (HWND HWND, LPARAM LPARAM)

{

Handle H = getProp (hwnd, g_szpropname);

IF (h == g_hvalue)

{

* (Hwnd *) lparam = hwnd;

Return False;

}

Return True;

} 3, add attributes in the ONINITDIALOG () of the main window

// Set the window properties

SetProp (m_hwnd, g_szpropname, g_hvalue);

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

New Post(0)