Created
January 11, 2012 11:53
-
-
Save t-mat/1594339 to your computer and use it in GitHub Desktop.
Windows SDK : Mutexを用いて、同一アプリケーションの複数起動を判別する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Mutexを用いて、同一アプリケーションの複数起動を判別する | |
| /* | |
| 使い方: | |
| INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, INT) { | |
| CheckExistingInstance exin("Your App's Unique Identifier String"); | |
| if(exin.isExist()) { | |
| return 0; // 既に存在したので、何もせずに終了 | |
| } | |
| ... | |
| }; | |
| セッションをまたいで(同一マシンの複数ユーザ間で)1つだけにしたい場合、 | |
| mutex名を "Global\\" で始めること。詳細は CreateMutex の lpName の説明を参照。 | |
| @seealso | |
| CreateMutex | |
| http://msdn.microsoft.com/en-us/library/windows/desktop/ms682411(v=vs.85).aspx | |
| */ | |
| class CheckExistingInstance { | |
| public: | |
| CheckExistingInstance(const char* uniqueString) | |
| : h(INVALID_HANDLE_VALUE) | |
| , e(false) | |
| { | |
| h = CreateMutex(0, 0, uniqueString); | |
| if(GetLastError() == ERROR_ALREADY_EXISTS) { | |
| e = true; | |
| CloseHandle(h); | |
| h = INVALID_HANDLE_VALUE; | |
| } | |
| } | |
| ~CheckExistingInstance() { | |
| if(h != INVALID_HANDLE_VALUE) { | |
| CloseHandle(h); | |
| h = INVALID_HANDLE_VALUE; | |
| } | |
| } | |
| bool isExist() const { | |
| return e; | |
| } | |
| protected: | |
| HANDLE h; | |
| bool e; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment