单实例程序(用户点击另一个的时候,再次显示该程序)

来源:互联网 发布:ajax循环遍历map数据 编辑:程序博客网 时间:2024/06/08 11:13

http://www.cnblogs.com/kenter/archive/2010/12/24/1916363.html


复制代码
// SingleInstanceApp.cpp : header file
//
// CWinApp with single-instance support
//
// Copyright (C) 1997, 1998 Giancarlo Iovino (giancarlo@saria.com)
// All rights reserved. May not be sold for profit.
//
// Thanks to Kevin Lussier for the base idea.
//
// This code was developed for MFC Programmers SourceBook
// (http://www.codeguru.com)
//

#ifndef __AFXWIN_H__
    
#error include 'stdafx.h' before including this file for PCH
#endif

#include 
"resource.h"       // main symbols

/////////////////////////////////////////////////////////////////////////////
// CSingleInstanceApp:
//

class CSingleInstanceApp : public CWinApp
{
public:
    
// Construction/Destruction
    CSingleInstanceApp();
    
~CSingleInstanceApp();

    
// Operations
    BOOL CheckSingleInstance(UINT nID);
    CString GetClassName() 
const;

protected:
    HANDLE m_hMutex;
    CString m_strClassName;
};


/////////////////////////////////////////////////////////////////////////////
复制代码

 

 

复制代码
// SingleInstanceApp.cpp : implementation file
//
// CWinApp with single-instance support
//
// Copyright (C) 1997, 1998 Giancarlo Iovino (giancarlo@saria.com)
// All rights reserved. May not be sold for profit.
//
// Thanks to Kevin Lussier for the base idea.
//
// This code was developed for MFC Programmers SourceBook
// (http://www.codeguru.com)
//

#include 
"stdafx.h"
#include 
"SingleInstanceApp.h"
#define _AFX_NO_OLE_SUPPORT
#include 
<../mfc/src/afximpl.h>

CSingleInstanceApp::CSingleInstanceApp()
{
    
// Set our default values
    m_hMutex = NULL;
}

CSingleInstanceApp::
~CSingleInstanceApp()
{
    
// Release the mutex
    if ( m_hMutex != NULL ) {
        ReleaseMutex( m_hMutex );
    }
}

BOOL CSingleInstanceApp::CheckSingleInstance(UINT nID) {
    CString strFullString;

    
// Generate a synthetic name for this class using the
    
// AfxRegisterWndClass convention
    HINSTANCE hInst = AfxGetInstanceHandle();
    UINT nClassStyle 
= CS_DBLCLKS;    
    HCURSOR hCursor 
= LoadCursor(IDC_ARROW );
    HICON    hIcon 
= LoadIcon(MAKEINTRESOURCE( nID ) );    

    LPCTSTR lpstrAppName 
= AfxGetAppName();
    ASSERT(lpstrAppName 
!= NULL);

    
if (hCursor == NULL && hIcon == NULL)
        m_strClassName.Format(_T(
"%s:%x:%x"), lpstrAppName,
            (UINT)hInst, nClassStyle);
    
else
        m_strClassName.Format(_T(
"%s:%x:%x:%x:%x"), lpstrAppName,
            (UINT)hInst, nClassStyle, (UINT)hCursor, (UINT)NULL);
    
    
// Create the mutex with the class name
    m_hMutex = CreateMutex(NULL, FALSE, m_strClassName);
    
// Check for errors
    if ( GetLastError() == ERROR_ALREADY_EXISTS ) {
        
// Reset our mutex handle (just in case)
        m_hMutex = NULL;
        
// The mutex already exists: an instance is already
        
// running. Find the app window and bring it to foreground
        HWND hWnd = FindWindowEx(NULL, NULL, m_strClassName, NULL);
        
if ( hWnd != NULL ) {
            ShowWindow( hWnd, SW_RESTORE );
            BringWindowToTop( hWnd );
            SetForegroundWindow( hWnd );
        }
    
        
// Return failure
        return FALSE;
    }

    
// Register the unique window class name
    WNDCLASS wndclass;    
    ZeroMemory(
&wndclass, sizeof(WNDCLASS));

    wndclass.style 
= nClassStyle;
    wndclass.lpfnWndProc 
= AfxWndProc;
    wndclass.hInstance 
= hInst;
    wndclass.hIcon 
= hIcon; 
    wndclass.hCursor 
= hCursor;
    wndclass.hbrBackground 
= NULL;
    wndclass.lpszMenuName 
= NULL;
    wndclass.lpszClassName 
= m_strClassName; // The class name
    
    
// Use AfxRegisterClass to register the class, exit if it fails
    if(!AfxRegisterClass(&wndclass)) {
        AfxMessageBox( _T(
"Failed to register window class!"), MB_ICONSTOP | MB_OK );
        
// Return failure
        return FALSE;
    }

    
// Return success
    return TRUE;
}

CString CSingleInstanceApp::GetClassName() 
const
{
    
return m_strClassName;
}
复制代码

 

 

使用:

调用 #include "SingleInstanceApp.h"

class CTestSingleApp : public CSingleInstanceApp 继承

 

复制代码
BOOL CTestSingleApp::InitInstance()
{
    AfxEnableControlContainer();

    
//判断单例运行
    BOOL bSingleInstance = CheckSingleInstance(IDR_MAINFRAME);    

    
// Standard initialization
    
// If you are not using these features and wish to reduce the size
    
//  of your final executable, you should remove from the following
    
//  the specific initialization routines you do not need.

#ifdef _AFXDLL
    Enable3dControls();            
// Call this when using MFC in a shared DLL
#else
    Enable3dControlsStatic();    
// Call this when 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(CTestSingleDoc),
        RUNTIME_CLASS(CMainFrame),       
// main SDI frame window
        RUNTIME_CLASS(CTestSingleView));
    AddDocTemplate(pDocTemplate);

    
// Parse command line for standard shell commands, DDE, file open
    CCommandLineInfo cmdInfo;
    ParseCommandLine(cmdInfo);

    
//保证单例子
    if (!bSingleInstance) {
        AfxMessageBox(
"此程序已运行!");
        
return FALSE;
    }

    
// Dispatch commands specified on the command line
    if (!ProcessShellCommand(cmdInfo))
        
return FALSE;

    
// The one and only window has been initialized, so show and update it.
    m_pMainWnd->ShowWindow(SW_SHOW);
    m_pMainWnd
->UpdateWindow();

    
return TRUE;
}
复制代码

 

 

 代码下载:http://files.cnblogs.com/kenter/TestSingle.zip





还可以用registerwindowmessage的方式注册一个消息, bringwindowtotop和 setforegroundwindow

原创粉丝点击