首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> 關於VC++

為對話框應用程式加入啟動畫面:CSplashWnd 類別完整實作與使用教學

     編輯:關於VC++

前言

MFC AppWizard 產生的「啟動畫面」元件僅支援有框架視窗 (CMainFrame) 的專案,對話框型專案無法直接使用。本文提供一個獨立的 CSplashWnd 類別,支援位圖資源、任意逾時時間、父視窗指定,並可同時用於對話框與 SDI/MDI 專案。

CSplashWnd 類別設計

  • 繼承 CWnd,建立 WS_POPUP | WS_VISIBLE 視窗。
  • 建構子載入位圖資源 (IDB_SPLASH24 等),取得寬高置中顯示。
  • 提供靜態函數 ShowSplashScreen(UINT timeout, UINT bitmapID, CWnd* pParent) 一鍵顯示。
  • 覆寫 PreTranslateAppMessage 攔截鍵盤/滑鼠訊息自動關閉。

三步驟整合到對話框專案

步驟 1:修改 CDialog::OnInitDialog

在 OnInitDialog 末尾加入:


// 顯示啟動畫面 3 秒,使用位圖資源 IDB_SPLASH24,父視窗為 this
CSplashWnd::ShowSplashScreen(3000, IDB_SPLASH24, this);

步驟 2:修改 CWinApp::InitInstance

在函數開頭加入命令列解析與啟用:


CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
CSplashWnd::EnableSplashScreen(cmdInfo.m_bShowSplash);

步驟 3:覆寫 CWinApp::PreTranslateMessage

用 ClassWizard 加入 PreTranslateMessage 虛擬函數:


BOOL CMyApp::PreTranslateMessage(MSG* pMsg) {
    if (CSplashWnd::PreTranslateAppMessage(pMsg)) return TRUE;
    return CWinApp::PreTranslateMessage(pMsg);
}

CSplashWnd 核心程式碼摘要

Splash.h


class CSplashWnd : public CWnd {
public:
    CSplashWnd(UINT nBitmapID);           // 載入位圖資源
    static void ShowSplashScreen(UINT timeout, UINT nBitmapID, CWnd* pParent);
    static BOOL PreTranslateAppMessage(MSG* pMsg);
    static void EnableSplashScreen(BOOL bEnable);
protected:
    afx_msg int OnCreate(LPCREATESTRUCT);
    afx_msg void OnPaint();
    afx_msg void OnTimer(UINT nIDEvent);
    DECLARE_MESSAGE_MAP()
private:
    CBitmap m_bmp; UINT m_nTimeout; BOOL m_bEnabled;
};

Splash.cpp 關鍵實作

  • OnCreate:CenterWindow() 置中,SetTimer(1, m_nTimeout, NULL) 設定自動關閉計時器。
  • OnPaint:CPaintDC 配合 CDC::DrawState 或 BitBlt 繪製位圖。
  • OnTimer:KillTimer、DestroyWindow() 關閉視窗。
  • PreTranslateAppMessage:偵測 WM_KEYDOWN, WM_LBUTTONDOWN 等訊息提前關閉。

進階用法

  • 若需在啟動畫面顯示初始化進度文字,可加入 SetText(LPCTSTR) 並 Invalidate() 重繪。
  • 支援 PNG/JPG 等格式可搭配 IPicture (OLE) 或 GDI+ 載入。

總結

CSplashWnd 只需三步驟即可為任何 MFC 專案(含對話框型)加入專業啟動畫面,程式碼精簡、無 MFC 版本相依性問題,適合直接整合至現有專案。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved