Introduction
Ever wanted to display a splash bitmap when starting your WTL app? Well here's how - and you only need to add two lines of code to your project! Marvellous.
First include the header file:
#include "splashwnd.h"
Then, in your apps Run
function simply create a new CSplashWnd
object after creating your main window, passing it the resource ID of the image you want to display:
new CSplashWnd(IDB_SPLASH);
That's it! It couldn't be much easier.
You can also supply a timeout value and the handle of an existing window (used when centering the splash) to the constructor. For example, to display the splash for 3 seconds, centered over your main window:
if(wndMain.CreateEx() == NULL)
{
ATLTRACE(_T("Main window creation failed!\n"));
return 0;
}
wndMain.ShowWindow(nCmdShow);
new CSplashWnd(IDB_SPLASH, 3000, wndMain.m_hWnd);
Note that you can dispense with the splash window by left/right-clicking it with the mouse or by pressing ESC.
CSplashWnd
Here is the source:
#pragma once
#include <atlmisc.h>
class CSplashWnd :
public CWindowImpl<CSplashWnd, CWindow,
CWinTraits<WS_POPUP|WS_VISIBLE, WS_EX_TOOLWINDOW> >
{
private:
enum
{
DEF_TIMER_ID = 1001,
DEF_TIMER_ELAPSE = 2500,
};
private:
CBitmap m_bmp;
int m_nTimeout;
HWND m_hParent;
public:
CSplashWnd(UINT nBitmapID, int nTimeout = DEF_TIMER_ELAPSE,
HWND hParent = NULL)
: m_nTimeout(nTimeout)
, m_hParent(hParent)
{
if (!m_bmp.LoadBitmap(nBitmapID))
{
ATLTRACE(_T("Failed to load spash bitmap\n"));
return;
}
CSize size;
if (!m_bmp.GetSize(size))
{
ATLTRACE(_T("Failed to get spash bitmap size\n"));
return;
}
CRect rect(0, 0, size.cx, size.cy);
if (!Create(NULL, rect))
{
ATLTRACE(_T("Failed to create splash window\n"));
return;
}
UpdateWindow();
}
virtual void OnFinalMessage(HWND )
{
delete this;
}
BEGIN_MSG_MAP(CSplashWnd)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_PAINT, OnPaint)
MESSAGE_HANDLER(WM_TIMER, OnTimer)
MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBkgnd)
MESSAGE_HANDLER(WM_LBUTTONDOWN, OnButtonDown)
MESSAGE_HANDLER(WM_RBUTTONDOWN, OnButtonDown)
MESSAGE_HANDLER(WM_KEYDOWN, OnKeyDown)
END_MSG_MAP()
LRESULT OnCreate(UINT , WPARAM ,
LPARAM , BOOL& )
{
CenterWindow(m_hParent);
SetTimer(DEF_TIMER_ID, m_nTimeout);
return 0;
}
LRESULT OnPaint(UINT , WPARAM ,
LPARAM , BOOL& )
{
CPaintDC dc(m_hWnd);
CDC dcImage;
if (dcImage.CreateCompatibleDC(dc.m_hDC))
{
CSize size;
if (m_bmp.GetSize(size))
{
HBITMAP hBmpOld = dcImage.SelectBitmap(m_bmp);
dc.BitBlt(0, 0, size.cx, size.cy, dcImage, 0, 0, SRCCOPY);
dcImage.SelectBitmap(hBmpOld);
}
}
return 0;
}
LRESULT OnTimer(UINT , WPARAM ,
LPARAM , BOOL& )
{
KillTimer(DEF_TIMER_ID);
PostMessage(WM_CLOSE);
return 0;
}
LRESULT OnEraseBkgnd(UINT , WPARAM ,
LPARAM , BOOL& )
{
return TRUE;
}
LRESULT OnButtonDown(UINT , WPARAM ,
LPARAM , BOOL& )
{
PostMessage(WM_CLOSE);
return 0;
}
LRESULT OnKeyDown(UINT , WPARAM wParam,
LPARAM , BOOL& )
{
if (wParam == VK_ESCAPE)
PostMessage(WM_CLOSE);
return 0;
}
};