一、重写父类的成员虚函数
1、在应用程序框架中声明虚函数InitApplication()
class CMyWinApp : public CWinApp { public: CMyWinApp(); virtual BOOL InitInstance(); virtual BOOL InitApplication(); virtual int Run(); virtual BOOL OnIdle(LONG ICount); virtual int ExitInstance(); };
2、重写该方法
int CMyWinApp::ExitInstance() { AfxMessageBox("善后处理"); return CWinApp::ExitInstance(); } BOOL CMyWinApp::OnIdle(LONG ICount) { //AfxMessageBox("空闲处理");//死循环 return CWinApp::OnIdle(ICount); } int CMyWinApp::Run() { CWinApp::Run(); AfxMessageBox("消息循环"); return 0; } BOOL CMyWinApp::InitApplication() { AfxMessageBox("初始化"); return CWinApp::InitApplication(); }
运行结果:
先弹窗初始化,再弹窗善后处理,再弹窗消息新欢
二、窗口创建
BOOL CMyWinApp::InitInstance() {//此函数中的this为&theApp CMyFrameWnd* pFrame = new CMyFrameWnd; pFrame->Create(NULL, "测试"); this->m_pMainWnd = pFrame; //pFrame->ShowWindow(SW_SHOW);//相当于下面的语句 ::ShowWindow(pFrame->m_hWnd, SW_SHOW); //pFrame->UpdateWindow();相当于下面的语句 ::UpdateWindow(pFrame->m_hWnd); return TRUE; }
运行结果:
三、创建窗口处理函数
class CMyFrameWnd : public CFrameWnd { public: virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); //声明虚函数 }; //实现虚函数 LRESULT CMyFrameWnd::WindowProc( UINT message, WPARAM wParam, LPARAM lParam) {//此函数的this为pFrame switch (message) { case WM_CREATE: AfxMessageBox("WM_CREATE消息被处理"); break; case WM_PAINT: { PAINTSTRUCT ps = { 0 }; HDC hdc = ::BeginPaint(this->m_hWnd, &ps); ::TextOut(hdc, 100, 100, "hello", 5); ::EndPaint(this->m_hWnd, &ps); } } return CFrameWnd::WindowProc(message, wParam, lParam); }
运行结果:
四、跟随鼠标移动,鼠标到那,创建的窗口到那
关键代码
class CMyFrameWnd : public CFrameWnd { public: virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); int m_x; int m_y; }; case WM_MOUSEMOVE: { m_x = LOWORD(lParam);//wParam传递的是否按左键右键ctrl等键 m_y = HIWORD(lParam); ::InvalidateRect(this->m_hWnd, NULL, TRUE);//重画 }