summaryrefslogtreecommitdiff
path: root/Common/OneInstance.h
blob: 5eec36f88cdf2161b0b6ac9b24570dee85ae15fa (plain)
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
// OneInstance.h: interface for the COneInstance class.
//
//////////////////////////////////////////////////////////////////////


#if !defined(AFX_ONEINSTANCE_H__A3059F66_BFED_11D2_A501_0020182B97FC__INCLUDED_)
#define AFX_ONEINSTANCE_H__A3059F66_BFED_11D2_A501_0020182B97FC__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include <string>

class COneInstance
{
public:

	// Constructor
	COneInstance(LPCSTR szID) 
		: sMtxName(szID) {};

	// Activates a Window based on the following...
	// szClass:		Class name of Window (get from SPY)
	// szTitle:		Title bar of Window
	bool FindAndActivate(LPCSTR szClass, LPCSTR szTitle) const
	{
		// Search for the Window
		HWND hWnd = ::FindWindow(szClass, szTitle);

		// Check if we have any popups
		HWND hChild = GetLastActivePopup(hWnd);

		bool bRet = SetForegroundWindow(hWnd) ? true : false; // bring main window to top

		if (hWnd != hChild)
			SetForegroundWindow(hChild); // a pop-up window is active
										 // bring it to the top too
										 // do not run second instance
		return bRet;
	}

	// Checks if there is already a program loaded 
	// with the ID passed when creating COneInstance
	bool IsAlreadyLoaded() const
	{
		if(sMtxName.empty())
			return false;

		// Use a Mutex and not a FindWindow because process could exist
		// without a Window (
		::CreateMutex(NULL, true, sMtxName.c_str()); 

		// mutex will be automatically deleted when process ends
		return (::GetLastError() == ERROR_ALREADY_EXISTS);
	}


protected:
	std::string sMtxName;
};

#endif // !defined(AFX_ONEINSTANCE_H__A3059F66_BFED_11D2_A501_0020182B97FC__INCLUDED_)