标准的对话框类都以“#32770”作为类名,当然常规的应用没有任何问题,但是如果FindWindow查找窗口时就比较容易造成困扰。下面就来介绍下自定义对话框类的简单方法。
首先第一步 修改资源 .rc 文件中的类名,添加CLASS "你想要的类名"
IDD_DLG7_DIALOG DIALOGEX 0, 0, 133, 69
STYLE DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
EXSTYLE WS_EX_APPWINDOW
CAPTION "Dlg7"
CLASS "myDefWndClass"
FONT 9, "宋体"
BEGIN
END
第二步,在创建对话框之前注册自定义类名
WNDCLASSEX ws = { sizeof(WNDCLASSEX) };
GetClassInfoEx(hInst, _T("#32770"), &ws);
ws.lpszClassName = _T("myDefWndClass");
VERIFY( RegisterClassEx(&ws) );
上面两步就完成了自定义类名的过程。
下面的代码从资源中提取类名,如果不是默认的话就注册,等于替代了第二步,比较具有些通用性。
//从资源获取对话框类名称
CString __cdecl GetDialogWndClassName(HINSTANCE hInst, LPCTSTR m_lpszTemplateName)
{
CString wndClass;
#pragma pack(push, 1)
typedef struct
{
WORD dlgVer;
WORD signature;
DWORD helpID;
DWORD exStyle;
DWORD style;
WORD cDlgItems;
short x;
short y;
short cx;
short cy;
} _DLGTEMPLATEEX;
#pragma pack(pop)
do
{
HRSRC hResource = FindResource(hInst, m_lpszTemplateName, RT_DIALOG);
if(hResource == NULL)
break;
HGLOBAL hDialogTemplate = LoadResource(hInst, hResource);
if(hDialogTemplate == NULL)
break;
DLGTEMPLATE *pTemplate = (DLGTEMPLATE*)LockResource(hDialogTemplate);
BOOL bDialogEx = ((_DLGTEMPLATEEX*)pTemplate)->signature == 0xFFFF;
WORD* pw;
if (bDialogEx)
pw = (WORD*)((_DLGTEMPLATEEX*)pTemplate + 1);
else
pw = (WORD*)(pTemplate + 1);
if (*pw == 0xFFFFU) // Skip menu name string or ordinal
pw += 2; // WORDs
else
while(*pw++);
if (*pw == 0xFFFFU) // Skip class name string or ordinal
pw += 2; // WORDs
else
{
wndClass = (WCHAR*)pw;
while(*pw++);
}
//while (*pw++); // Skip caption string
UnlockResource(hDialogTemplate);
FreeResource(hDialogTemplate);
} while (0);
return wndClass;
}
//注册自定义对话框类名
BOOL RegMyDialogClass(HINSTANCE hInst, LPCTSTR m_lpszTemplateName)
{
BOOL bRet = FALSE;
CString szWndClass = GetDialogWndClassName(hInst, m_lpszTemplateName);
if(!szWndClass.IsEmpty())
{
WNDCLASSEX ws = { sizeof(WNDCLASSEX) };
GetClassInfoEx(hInst, _T("#32770"), &ws);
ws.lpszClassName = szWndClass;
VERIFY( RegisterClassEx(&ws) );
}
return bRet;
}
CDlg7Dlg::CDlg7Dlg(CWnd* pParent /*=NULL*/)
: CDialog(CDlg7Dlg::IDD, pParent)
{
RegMyDialogClass(AfxGetResourceHandle(), m_lpszTemplateName);
//{{AFX_DATA_INIT(CDlg7Dlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
} |