基于对话框的单实例应用程序

介绍

有许许多多的文章介绍单示例应用程序的实现,这里演示一种非常简单的基于MFC对话框的应用程序,本技术可以运用到ATL/WTL和普通的win32应用程序。

实现

创建一个基于对话框的MFC工程。

打开资源文件(.rc),找到主窗口的模板,并添加一句话。把这个窗口类注册为SINGLE_INSTANCE_APP。

IDD_SINGLEINSTANCE_DIALOG DIALOGEX 0, 0, 320, 200
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
EXSTYLE WS_EX_APPWINDOW
CLASS "SINGLE_INSTANCE_APP"
CAPTION “Single Instance Application”
FONT 8, “MS Shell Dlg”, 0, 0, 0x1
BEGIN
DEFPUSHBUTTON “OK”,IDOK,263,7,50,16
PUSHBUTTON “Cancel”,IDCANCEL,263,25,50,16
CTEXT “TODO: Place dialog controls here.”,IDC_STATIC,10,96,300,8
END

然后在InitInstance()函数起始位置加入如下代码:

//register window class name
WNDCLASS wc = {0};
wc.style = CS_BYTEALIGNWINDOW|CS_SAVEBITS|CS_DBLCLKS;
wc.lpfnWndProc = DefDlgProc;
wc.cbWndExtra = DLGWINDOWEXTRA;
wc.hInstance = m_hInstance;
wc.hIcon = LoadIcon(IDR_MAINFRAME);
wc.hCursor = ::LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = CreateSolidBrush(GetSysColor(COLOR_BTNFACE));
wc.lpszClassName = _T(“SINGLE_INSTANCE_APP”); //this name is from dialog’s template

ATOM cls = RegisterClass(&wc);

//check if our program is running already
CWnd* pWnd = CWnd::FindWindow(_T(“SINGLE_INSTANCE_APP”), NULL);
if (pWnd)
{
pWnd->ShowWindow(SW_SHOW);
pWnd->SetForegroundWindow();
return FALSE;
}

OK,测试一下吧!

你可能感兴趣的:(MFC)