VS2012中,为MFC程序添加启…

来源:互联网 发布:方维互动直播系统源码 编辑:程序博客网 时间:2024/06/17 04:58
原文地址:VS2012中,为MFC程序添加启动画面作者:李小潴_MrJ
本文是读者在学习孙鑫的《VC++深入详解》时,对一些在VS2012与VC6.0不同地方,需要修改的代码进行整理得到的。
在VC6.0时代,我们通过在MFC工程中插入Splash组件来简单方便的实现这个功能,但在VS2012没有这个功能,所以如果想给自己的程序添加一个显示Logo的启动画面,就需要自己添加代码来实现,参考了下VC6.0中这个Splash组件添加后的代码,就很容易在自己的项目里实现这个功能。
首先,在菜单的“项目”中选择“类向导”,“添加类”,生成一个启动画面的Splash类。
[转载]VS2012中,为MFC程序添加启动画面
[转载]VS2012中,为MFC程序添加启动画面

然后,实现代码主要是在CSplashWnd类的头文件和源文件中实现。在CSplashWnd类的头文件中我们添加下面的代码:
#pragma once
#include "afxwin.h"

class CSplashWnd :
 publicCWnd
{
public:
 CSplashWnd(void);
 ~CSplashWnd(void);
 CBitmapm_bitmap;
 static voidShowSplashScreen(CWnd* pParentWnd = NULL);
protected:
 BOOL Create(CWnd* pParentWnd= NULL); 
 static CSplashWnd*c_pSplashWnd;
public:
 DECLARE_MESSAGE_MAP()
 afx_msg intOnCreate(LPCREATESTRUCT lpCreateStruct);
 afx_msg voidOnPaint();
 afx_msg voidOnTimer(UINT_PTR nIDEvent);
};



CSplashWnd类的源文件中我们添加下面的代码:
#include "stdafx.h"
#include "SplashWnd.h"
#include "resource.h"

CSplashWnd*CSplashWnd::c_pSplashWnd;

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

CSplashWnd::CSplashWnd(void)
{
}

CSplashWnd::~CSplashWnd(void)
{
}

void CSplashWnd::ShowSplashScreen(CWnd*pParentWnd)
{
 c_pSplashWnd = newCSplashWnd;
 if(!c_pSplashWnd->Create(pParentWnd))
  deletec_pSplashWnd;
 else
 c_pSplashWnd->UpdateWindow();
}

BOOL CSplashWnd::Create(CWnd*pParentWnd)
{
 if(!m_bitmap.LoadBitmap(IDB_BITMAP1))
  returnFALSE;

 BITMAPbm;
 m_bitmap.GetBitmap(&bm);

 returnCreateEx(0,
  AfxRegisterWndClass(0,AfxGetApp()->LoadStandardCursor(IDC_ARROW)),
  NULL, WS_POPUP |WS_VISIBLE, 0, 0, bm.bmWidth, bm.bmHeight,pParentWnd->GetSafeHwnd(), NULL);
 return0;
}

int CSplashWnd::OnCreate(LPCREATESTRUCTlpCreateStruct)
{
 if(CWnd::OnCreate(lpCreateStruct) == -1)
  return-1;

 // TODO: 在此添加您专用的创建代码
 // Center thewindow.
 CenterWindow();

 // Set a timer to destroythe splash screen.
 SetTimer(1, 3000, NULL);   

 return0;
}

void CSplashWnd::OnPaint()
{
 CPaintDC dc(this); // devicecontext for painting
 // TODO:在此处添加消息处理程序代码
 // 不为绘图消息调用CWnd::OnPaint()
 CDCdcImage;
 if(!dcImage.CreateCompatibleDC(&dc))
  return;

 BITMAPbm;
 m_bitmap.GetBitmap(&bm);

 // Paint theimage.
 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_PTRnIDEvent)
{
 // TODO:在此添加消息处理程序代码和/或调用默认值
 DestroyWindow();
 AfxGetMainWnd()->UpdateWindow();

 CWnd::OnTimer(nIDEvent);
}

使用方法: 
再app和mainFram对应的cpp文件中包含头文件SplashWnd.h,需在MFC工程中的CMainFrame类中添加消息OnCreate,并在函数定义中添加语句CSplashWnd::ShowSplashScreen(this);同时把位图资源添加进去,并设置好logo消隐时间即可。

0 0