PSS ID Number: 109175
Article Last Modified on 6/15/2004
141752 SAMPLE: Limiting 32-bit Applications to a Single Instance
119591 How to Obtain Microsoft Support Files from Online Services
141752 SAMPLE: Limiting 32-bit Applications to a Single Instance
BOOL COnetimeApp::InitApplication()
{
// Base class version actually does nothing.
CWinApp::InitApplication();
WNDCLASS wndcls;
// Start with NULL defaults.
memset(&wndcls, 0, sizeof(WNDCLASS));
// Retrieve WNDCLASS structure for default window class.
::GetClassInfo(AfxGetInstanceHandle(),"AfxFrameOrView",&wndcls);
// Give new class a unique name.
wndcls.lpszClassName = "MyNewClass";
// Register new class and return result from ::RegisterClass().
return ::RegisterClass(&wndcls);
}
Sample code to override CWinApp::InitInstance() to check for (and
activate) any previous instance of the application:
BOOL COnetimeApp::InitInstance()
{
// If this isn't the first instance, return FALSE
// immediately. FirstInstance() will have already
// activated the previous instance.
if (!FirstInstance())
return FALSE;
SetDialogBkColor(); // Set dialog box background color to gray.
.
. // Continue with normal InitInstance code...
.
}
Sample code to add a member function to your CWinApp-derived class that
actually does the work of checking for and activating a previous instance:
BOOL COnetimeApp::FirstInstance()
{
CWnd *PrevCWnd, *ChildCWnd;
// Determine if another window with our class name exists...
if (PrevCWnd = CWnd::FindWindow("MyNewClass",NULL))
{
// if so, does it have any popups?
ChildCWnd=PrevCWnd->GetLastActivePopup();
// Bring the main window to the top.
PrevCWnd->BringWindowToTop();
// If iconic, restore the main window.
if (PrevCWnd->IsIconic())
PrevCWnd->ShowWindow(SW_RESTORE);
// If there was an active popup, bring it along too
if (PrevCWnd != ChildCWnd)
ChildCWnd->BringWindowToTop();
// Return FALSE. This isn't the first instance
// and you finished activating the previous one.
return FALSE;
}
else
return TRUE; // First instance. Proceed as normal.
}
Sample code to override CFrameWnd::PreCreateWindow() to use your window
class instead of the one registered automatically by MFC:
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
cs.lpszClass = "MyNewClass";
return TRUE;
}
Additional query words: kbNoUpdate
Keywords: kbdownload kbArchitecture kbsample KbUIDesign KB109175
Technology: kbAudDeveloper kbMFC kbvc100 kbvc150 kbVC151 kbVC152 kbVC16bitSearch kbVC200 kbVC210 kbVC32bitSearch kbVCsearch