方法一(MFC适用)、
BOOL CXXXApp::InitInstance()
{
// keep only one program running
HANDLE hSem = CreateSemaphore(NULL, 1, 1, m_pszExeName);
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
CloseHandle(hSem);
HWND hWndPrevious = GetWindow(::GetDesktopWindow(), GW_CHILD);
while (IsWindow(hWndPrevious))
{
if (GetProp(hWndPrevious, m_pszExeName))
{
if (IsIconic(hWndPrevious))
{
ShowWindow(hWndPrevious, SW_RESTORE);
}
SetForegroundWindow(hWndPrevious);
SetForegroundWindow(::GetLastActivePopup(hWndPrevious));
return FALSE;
}
hWndPrevious = GetWindow(hWndPrevious, GW_HWNDNEXT);
}
return FALSE;
}
//......
}
int CXXXDlg::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDialogEx::OnCreate(lpCreateStruct) == -1)
return -1;
// TODO: Add your specialized creation code here
SetProp(m_hWnd, AfxGetApp()->m_pszExeName, (HANDLE)1);
return 0;
}
void CXXXDlg::OnDestroy()
{
CDialogEx::OnDestroy();
// TODO: Add your message handler code here
RemoveProp(m_hWnd, AfxGetApp()->m_pszExeName);
}
方法二(MFC适用)、
BOOL CXXXApp::InitInstance()
{
// keep only one program running
HANDLE hMutex = CreateMutex(NULL, FALSE, _T("unicode string"));
if (hMutex != NULL)
{
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
HWND oldHWnd = NULL;
oldHWnd = FindWindow(NULL, _T("dialog title"));
if (oldHWnd)
{
ShowWindow(oldHWnd, SW_SHOWNORMAL);
SetActiveWindow(oldHWnd);
BringWindowToTop(oldHWnd);
SetForegroundWindow(oldHWnd);
}
CloseHandle(hMutex);
hMutex = NULL;
return FALSE;
}
}
// ......
}
方法三(Win32程序适用)、
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hWnd = FindWindow(szWindowClass, szTitle);
if (hWnd)
{
// set focus to foremost child window
// The "| 0x00000001" is used to bring any owned windows to the foreground and
// activate them.
// SetForegroundWindow((HWND)((ULONG) hWnd | 0x00000001));
return FALSE;
}
// ......
}
方法四(全局互斥量,在程序入口使用即可)、
#pragma data_seg("Shared")
int volatile g_lAppInstance = 0;
#pragma data_seg()
#pragma comment(linker,"/section:Shared,RWS")
if (0 == g_lAppInstance)
{
g_lAppInstance = 1;
}
else if (1 == g_lAppInstance)
{
MessageBox(NULL, TEXT("Already running"), TEXT("warning"), MB_OK);
return FALSE;
}
else
{
// start it
}