MFC开发常见问题的回答2
第一辑在http://www.csdn.net/develop/read_article.asp?id=6676
1.如何让我的程序运行的时候最大化?
(1)在appwizard第4步选择“advanced"从中选择Mainframe的Maximized
(2)对于MDI程序,在CWinApp::InitInstance() 中做下面改动
// Create main MDI Frame window.
CMainFrame* pMainFrame = new CMainFrame;
if (!pMainFrame->LoadFrame(IDR_MAINFRAME))
return FALSE;
m_nCmdShow = SW_SHOWMAXIMIZED; // 注意添加此行!!!
pMainFrame->ShowWindow(m_nCmdShow);
pMainFrame->UpdateWindow();
m_pMainWnd = pMainFrame;
(3)对于SDI程序,在CWinApp::InitInstance() 中的OnFileNew()调用之前
m_nCmdShow = SW_SHOWMAXIMIZED;
// 下面创建空文档
OnFileNew();
2,如何给其他线程发消息?
用SendNotifyMessage() 函数。
3,如何让我的程序只运行一次?
const char* MyMainWndClassName = "MyMainWndXQW"
BOOL CMyApp::InitApplication()
{
// Call base class. Default version does nothing.
CWinApp::InitApplication();
WNDCLASS wndcls;
// Start with NULL defaults.
memset(&wndcls, 0, sizeof(WNDCLASS));
// Get class information for default window class.
::GetClassInfo(AfxGetInstanceHandle(),"AfxFrameOrView",&wndcls);
// Substitute unique class name for new class.
wndcls.lpszClassName = MyMainWndClassName;
// Register new class and return the result code.
return ::RegisterClass(&wndcls);
}
BOOL CMyApp::FirstInstance()
{
CWnd *PrevCWnd, *ChildCWnd;
// Determine if another window with our class name exists.
PrevCWnd = CWnd::FindWindow(MyMainWndClassName, NULL);
if (PrevCWnd != NULL)
{
// If so, does it have any pop-ups?
ChildCWnd=PrevCWnd->GetLastActivePopup();
// Bring the main window to the top.
PrevCWnd->BringWindowToTop();
// If iconic, restore the main window.
if (PrevCWnd->IsIconic())
PrevCWnd->ShowWindow(SW_RESTORE);
// If there are pop-ups, bring them along too!
if (PrevCWnd != ChildCWnd)
ChildCWnd->BringWindowToTop();
// Return FALSE. This isn't the first instance
// and we are done activating the previous one.
return FALSE;
}
else
// First instance. Proceed as normal.
return TRUE;
}
CMyApp::InitInstance()
{
if (!FirstInstance())
return FALSE;
// ...
}
4,MDI程序,关闭子窗口同时关闭父窗口,该如何做?
在子窗口的OnClose函数里添加
ASSERT(AfxGetMainWnd() != NULL);
AfxGetMainWnd()->SendMessage(WM_CLOSE);
菜单问题:
1,我在程序中用了MenuBar,结果找不到菜单了,我的方法是:
CMenu *menu;
menu = GetMenu()->GetSubMenu(0);
答:
AfxGetApp()->m_pMainWnd->GetMenu()->GetSubMenu(0);
2,如何动态修改MainFrame的菜单?
CMenu newMenu;
newMenu.LoadMenu (IDR_MENU1);
AfxGetMainWnd()->SetMenu( &newMenu );
AfxGetMainWnd()->DrawMenuBar();
newMenu.Detach ();