VS2013中使用MFC的时候添加启动画面

在学《VC++深入详解》这本书的时候,作者使用的是VC++6.0,然而我用的VS2013,很多地方都有了变化。

在9.8启动画面中,有很大的不同。百度之后,参考了网上一写代码(参考1,参考2),整理如下:

首先要使用类向导,创建一个MFC类CSplashWnd,基类是CWnd。

然后自己找一张Bmp放在工程的res文件夹下,并在VS->资源视图->点击右键,添加资源,选择bitmap,令其ID号为IDB_SPLASH.

然后CSplashWnd类的头文件和cpp文件如下:

SplashWnd.h

#pragma once


// CSplashWnd

class CSplashWnd : public CWnd
{
	DECLARE_DYNAMIC(CSplashWnd)

public:
	CSplashWnd();
	virtual ~CSplashWnd(); 
	virtual void PostNcDestroy();
	  

protected:
	afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
	afx_msg void OnPaint();
	afx_msg void OnTimer(UINT nIDEvent);
	DECLARE_MESSAGE_MAP()


protected:
	static CSplashWnd* m_pSplashWnd;//指向初始画面的指针
	bool Create(CWnd* pParentWnd);
	
public:
	CBitmap m_bitmap;//初始画面位图 
	static void ShowSplashScreen(CWnd* pParentWnd);
};


SplashWnd.cpp

// SplashWnd.cpp : 实现文件
//

#include "stdafx.h"
#include "Style.h"
#include "SplashWnd.h"


// CSplashWnd
CSplashWnd* CSplashWnd::m_pSplashWnd;

IMPLEMENT_DYNAMIC(CSplashWnd, CWnd)

CSplashWnd::CSplashWnd()
{

}

CSplashWnd::~CSplashWnd()
{
	ASSERT(m_pSplashWnd == this);
	m_pSplashWnd = NULL;
}


BEGIN_MESSAGE_MAP(CSplashWnd, CWnd)
	ON_WM_CREATE()
	ON_WM_PAINT()
	ON_WM_TIMER()
END_MESSAGE_MAP()



// CSplashWnd 消息处理程序

void CSplashWnd::ShowSplashScreen(CWnd* pParentWnd)
{
	if (m_pSplashWnd != NULL) return;
	m_pSplashWnd = new CSplashWnd;
	if (!m_pSplashWnd->Create(pParentWnd))
		//创建初始画面窗口   
		delete m_pSplashWnd;
	else
		m_pSplashWnd->UpdateWindow();
	//显示初始画面窗口   
}

bool CSplashWnd::Create(CWnd* pParentWnd)
{
	if (!m_bitmap.LoadBitmap(IDB_SPLASH))
		//载入位图   
		return FALSE;
	BITMAP bm; 
	m_bitmap.GetBitmap(&bm);
	return CreateEx(0, AfxRegisterWndClass(0, AfxGetApp()->LoadStandardCursor(IDC_ARROW)),
		NULL, WS_POPUP | WS_VISIBLE, 0, 0, bm.bmWidth, bm.bmHeight, pParentWnd->GetSafeHwnd(), NULL);//创建主框架窗口的子窗口
}

int CSplashWnd::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CWnd::OnCreate(lpCreateStruct) == -1)
		return -1;
	CenterWindow();
	SetTimer(1, 1000, NULL); //时间控制   

	return 0;
}

void CSplashWnd::OnPaint()
{
	CPaintDC dc(this);
	CDC dcImage;
	if (!dcImage.CreateCompatibleDC(&dc)) return;
	BITMAP bm;
	m_bitmap.GetBitmap(&bm);
	CBitmap* pOldBitmap = dcImage.SelectObject(&m_bitmap);
	dc.BitBlt(0, 0, bm.bmWidth, bm.bmHeight, &dcImage, 0, 0, SRCCOPY);
	dcImage.SelectObject(pOldBitmap);
}


void CSplashWnd::OnTimer(UINT_PTR nIDEvent)
{
	// TODO: Add your message handler code here and/or call default
	DestroyWindow(); //销毁初始画面窗口   
	AfxGetMainWnd()->UpdateWindow();
	CWnd::OnTimer(nIDEvent);
}

void CSplashWnd::PostNcDestroy(void)
{
	DestroyWindow();
	CWnd::PostNcDestroy();
}


然后再CMainFrame的实现文件MainFrm.cpp的OnCreate函数中调用

CSplashWnd::ShowSplashScreen(this);




你可能感兴趣的:(windows编程和MFC)