Let the application run only one instance of the implementation method _c language

Source: Internet
Author: User
Tags mutex

In our program to achieve similar "360 software Butler" function, it is necessary to solve two problems, first of all to determine that the program has an instance of running, followed by the running of the application instance to activate, while exiting the second application instance.

For the first question, we can determine that an instance of this program is running by setting a named mutex or a named Beacon object that detects a mutex or Beacon object when the program starts, such as a mutex or beacon object already exists.

The second question is how to find an instance of an application that is already running, and if we can find a pointer to a running instance main window, call SetForegroundWindow to activate the instance. We can find the main window of the running instance in two forms, one by calling FindWindowEx to find the handle of the running window, which is used more, and this article finds the handle of the running window in another form. By calling SetProp to set a tag on the main application window, you can use GetDesktopWindow to get a handle to a desktop window in a Windows environment, and the main window of all applications can be viewed as a child window of that window. Then we can use the GetWindow function to get the handles of these windows. Then use the Win32 SDK function Getprop to find out whether the main window of each application contains the tag we set, so we can find the first Instance main window we are looking for.

The following demo code is a single document application, for example, the project name is a mutex.

Copy Code code as follows:

1, in the Application class InitInstance () function to determine if an instance of an application is already running.

BOOL cmutexapp::initinstance ()

{

Creates a named Beacon object.

HANDLE Hsem=createsemaphore (null,1,1, "Restoration");

The IF (HSEM)//Beacon object was created successfully.

{

The Beacon object already exists, the program already has an instance running.

if (Error_already_exists==getlasterror ())

{

CloseHandle (Hsem); Closes the semaphore handle.

Gets a child window of the desktop window.

HWND Hwndprev=::getwindow (:: GetDesktopWindow (), gw_child);

while (:: IsWindow (Hwndprev))

{

Determine if the window has our pre-set tags, and if so, the window we are looking for and activate it.

if (:: Getprop (Hwndprev, "Restoration"))

{

If the main window is minimized, its size is restored.

if (:: Isiconic (Hwndprev))

:: ShowWindow (Hwndprev,sw_restore);

Activates the main window of the application.

:: SetForegroundWindow (Hwndprev);

return FALSE; Exits the instance.

}

Continue looking for the next window.

Hwndprev =:: GetWindow (Hwndprev,gw_hwndnext);

}

AfxMessageBox ("There is already an instance running, but can't find its main window!") ");

}

}

Else

{

AfxMessageBox ("Create Beacon object failed, program exits!") ");

return FALSE;

}

AfxEnableControlContainer ();

Standard initialization

If you are are not using this features and wish to reduce the size

of your final executable, your should remove from the following

The specific initialization routines you don't need.

#ifdef _afxdll

Enable3dcontrols (); Call the When using MFC in a shared DLL

#else

Enable3dcontrolsstatic (); Linking to MFC statically

#endif

Change the registry key under which our settings are stored.

Todo:you should modify this string to be something appropriate

such as the name of your company or organization.

Setregistrykey (_t ("Local appwizard-generated Applications"));

LoadStdProfileSettings (); Load standard INI file options (including MRU)

Register the application ' s document templates. Document templates

Serve as the connection between documents, frame windows and views.

Csingledoctemplate* pdoctemplate;

Pdoctemplate = new CSingleDocTemplate (

Idr_mainframe,

Runtime_class (Cmutexdoc),

Runtime_class (CMainFrame),//main SDI frame window

Runtime_class (Cmutexview));

AddDocTemplate (pdoctemplate);

Parse command line for standard shell commands, DDE, File Open

CCommandLineInfo Cmdinfo;

ParseCommandLine (Cmdinfo);

Dispatch commands specified on the command line

if (! ProcessShellCommand (Cmdinfo))

return FALSE;

The one and only Windows has been initialized, so show and update it.

M_pmainwnd->showwindow (Sw_show);

M_pmainwnd->updatewindow ();

return TRUE;

}

2, set the lookup tag in the OnCreate () function of the frame class.

int CMainFrame::OnCreate (lpcreatestruct lpcreatestruct)

{

if (cframewnd::oncreate (lpcreatestruct) = =-1)

return-1;

if (!m_wndtoolbar.createex (this, Tbstyle_flat, Ws_child | ws_visible | Cbrs_top

| Cbrs_gripper | Cbrs_tooltips | cbrs_flyby | Cbrs_size_dynamic) | |

!m_wndtoolbar.loadtoolbar (IDR_MAINFRAME))

{

TRACE0 ("Failed to create toolbar/n");

return-1; Fail to create

}

if (!m_wndstatusbar.create) | |

!m_wndstatusbar.setindicators (indicators,

sizeof (indicators)/sizeof (UINT))

{

TRACE0 ("Failed to create status bar/n");

return-1; Fail to create

}

Todo:delete These three lines if you don ' t want the toolbar to

Be dockable

M_wndtoolbar.enabledocking (Cbrs_align_any);

EnableDocking (Cbrs_align_any);

DockControlBar (&m_wndtoolbar);

Sets the lookup tag.

:: SetProp (M_hwnd, "Restoration", (HANDLE) 1);

return 0;

}

3, in the program exit is the deletion of the set of tags, in the framework class in response to Wm_destroy messages, processing.

void Cmainframe::ondestroy ()

{

Cframewnd::ondestroy ();

Todo:add your message Handler code here

Deletes the set of tags.

:: Removeprop (M_hwnd, "Restoration");

}

At this point, the ability to make an application run only one instance is complete.

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.