1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
#define PI_MSG 9999
#include <windows.h>
#include <string>
HANDLE hInstanceMutex;
LRESULT CALLBACK wProc (HWND,UINT,WPARAM,LPARAM);
const char *szClassName = "MySingleInstanceTestApp";
int WINAPI WinMain (HINSTANCE I,HINSTANCE PI,LPSTR Arg, int Show)
{
hInstanceMutex = CreateMutex(0,TRUE,szClassName);
if(hInstanceMutex)
{
if(GetLastError() == ERROR_ALREADY_EXISTS) // another instance is lurking
{
HWND inst = FindWindow(szClassName,0); // let's get the window handle
if(inst) // we found it
{
std::wstring arg_string;
int argc;
LPWSTR *argv = CommandLineToArgvW(GetCommandLineW(),&argc); // get argc,argv
if(argv) // we have arguments
{
for(int i = 0; i < argc; i++)
{
arg_string += argv[i]; // lets make them one line
arg_string += L" ";
}
SendMessage(inst,PI_MSG,0,(LPARAM)(LPWSTR)arg_string.c_str()); // pass to open instance
LocalFree(argv);
}
}
return 0; // we die, only single instance allowed
}
}
HWND hWnd;
MSG M;
WNDCLASSEX wcx;
ZeroMemory(&wcx,sizeof(WNDCLASSEX));
wcx.hInstance = I;
wcx.lpszClassName = szClassName;
wcx.lpfnWndProc = wProc;
wcx.style = CS_DBLCLKS;
wcx.cbSize = sizeof (WNDCLASSEX);
wcx.hIcon = LoadIcon(0,IDI_APPLICATION);
wcx.hIconSm = LoadIcon(0,IDI_APPLICATION);
wcx.hCursor = LoadCursor(0,IDC_ARROW);
wcx.hbrBackground = (HBRUSH) COLOR_BACKGROUND;
if (!RegisterClassEx(&wcx)) return 0; // fail
hWnd = CreateWindowEx (0,szClassName,"Single Instance Test Application",WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT,544,375,HWND_DESKTOP,0,I,0);
ShowWindow (hWnd,Show);
while(GetMessage(&M,0,0,0))
{
TranslateMessage(&M);
DispatchMessage(&M);
}
return M.wParam;
}
LRESULT CALLBACK wProc(HWND H,UINT M,WPARAM W,LPARAM L)
{
switch(M)
{
case PI_MSG: // another instance tried to start with arguments
{
LPWSTR pi_cmd = (LPWSTR)L; // stored argument string in LPARAM
if(pi_cmd)
{
MessageBoxW(H,pi_cmd,L"Message From Other Instance",MB_ICONASTERISK);
}
} break;
case WM_DESTROY:
{
PostQuitMessage(0);
} break;
default:
return DefWindowProc(H,M,W,L);
}
return 0;
}
|