第一步
添加类
class CUImageDC
{
public:
CUImageDC();
virtual ~CUImageDC();
void Delete();
void Create(int nWidth, int nHeight);
HDC GetSafeHdc(void){
return m_hDC;
}
HBITMAP GetBmpHandle(void){
return m_hBmp;
}
DWORD* GetBits(void){
return (DWORD*)m_pBits;
}
protected:
HBITMAP m_hBmp;
HDC m_hDC;
char* m_pBits;
};
CUImageDC::CUImageDC()
{
m_pBits = NULL;
m_hBmp = NULL;
m_hDC = NULL;
}
CUImageDC::~CUImageDC()
{
Delete();
}
void CUImageDC::Create(int nWidth, int nHeight)
{
BITMAPINFOHEADER bih;
memset(&bih, 0, sizeof(BITMAPINFOHEADER));
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biWidth = ((((int)nWidth * 8) + 31) & ~31) >> 3;
bih.biHeight = nHeight;
bih.biPlanes = 1;
bih.biBitCount = 32;
bih.biCompression = BI_RGB;
m_hBmp = NULL;
m_hDC = CreateCompatibleDC(NULL);
m_hBmp = ::CreateDIBSection(
GetSafeHdc(), (BITMAPINFO*)&bih,
DIB_RGB_COLORS, (void**)(&m_pBits), NULL, 0);
SelectObject(m_hDC, m_hBmp);
}
void CUImageDC::Delete()
{
if (m_hBmp)
DeleteObject(m_hBmp);
if (m_hDC)
DeleteDC(m_hDC);
}
第二步
创建变量
LPDIRECT3DSURFACE9 g_pd3dSurface = NULL;
CUImageDC g_dcSurface;
第三步
在创建好设备后添加
if (FAILED(g_D3DDevice->CreateRenderTarget(640, 480,
D3DFMT_A8R8G8B8, D3DMULTISAMPLE_NONE, 0,
/*!g_is9Ex*/false, // lockable
&g_pd3dSurface, NULL)))
{
return NULL;
}
g_D3DDevice->SetRenderTarget(0, g_pd3dSurface);
g_D3DDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
// turn off D3D lighting to use vertex colors
g_D3DDevice->SetRenderState(D3DRS_LIGHTING, FALSE);
// Enable alpha blending.
g_D3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
g_dcSurface.Create(640, -480);
SetWindowLong(hWnd, GWL_EXSTYLE, (GetWindowLong(hWnd, GWL_EXSTYLE) & ~WS_EX_TRANSPARENT) | WS_EX_LAYERED);
第四步
在渲染函数中添加
D3DLOCKED_RECT lockedRect;
RECT rc, rcSurface = {0, 0, 640, 480};
::GetWindowRect(hWnd, &rc);
POINT ptWinPos = { rc.left, rc.top};
POINT ptSrc = { 0, 0};
SIZE szWin = { 640, 480 };
BLENDFUNCTION stBlend = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
HDC hdcWnd = GetWindowDC(hWnd);
LPDIRECT3DSURFACE9 g_psysSurface = NULL;
g_D3DDevice->CreateOffscreenPlainSurface(640, 480,
D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM, &g_psysSurface, NULL);
g_D3DDevice->GetRenderTargetData(g_pd3dSurface, g_psysSurface);
g_psysSurface->LockRect(&lockedRect, &rcSurface, D3DLOCK_READONLY);
memcpy(g_dcSurface.GetBits(), lockedRect.pBits, 4 * 640 * 480);
UpdateLayeredWindow(hWnd, hdcWnd, &ptWinPos, &szWin, g_dcSurface.GetSafeHdc(), &ptSrc, RGB(255,255,255), &stBlend, ULW_ALPHA| ULW_COLORKEY);
g_psysSurface->UnlockRect();
g_psysSurface->Release();
完成后 窗体为透明色, 可以绘制各种无窗体的图形和文理