创建一个ICON需要两个掩码位图,AND and XOR masks
这个可以从
typedef struct _ICONINFO { BOOL fIcon; DWORD xHotspot; DWORD yHotspot; HBITMAP hbmMask; HBITMAP hbmColor; } ICONINFO;
中MSDN的解释看到,
代码如下:
////////////////////////////////////////////////////////////////////// // GetMaskBitmaps // Function to AND and XOR masks for a cursor from a HBITMAP. ////////////////////////////////////////////////////////////////////// void GetMaskBitmaps(HBITMAP hSourceBitmap, COLORREF clrTransparent, HBITMAP &hAndMaskBitmap, HBITMAP &hXorMaskBitmap) { HDC hDC = ::GetDC(NULL); HDC hMainDC = ::CreateCompatibleDC(hDC); HDC hAndMaskDC = ::CreateCompatibleDC(hDC); HDC hXorMaskDC = ::CreateCompatibleDC(hDC); //Get the dimensions of the source bitmap BITMAP bm; ::GetObject(hSourceBitmap,sizeof(BITMAP),&bm); hAndMaskBitmap = ::CreateCompatibleBitmap(hDC,bm.bmWidth,bm.bmHeight); hXorMaskBitmap = ::CreateCompatibleBitmap(hDC,bm.bmWidth,bm.bmHeight); //Select the bitmaps to DC HBITMAP hOldMainBitmap = (HBITMAP)::SelectObject(hMainDC,hSourceBitmap); HBITMAP hOldAndMaskBitmap = (HBITMAP)::SelectObject(hAndMaskDC,hAndMaskBitmap); HBITMAP hOldXorMaskBitmap = (HBITMAP)::SelectObject(hXorMaskDC,hXorMaskBitmap); //Scan each pixel of the souce bitmap and create the masks COLORREF MainBitPixel; for(int x=0;x<bm.bmWidth;++x) { for(int y=0;y<bm.bmHeight;++y) { MainBitPixel = ::GetPixel(hMainDC,x,y); if(MainBitPixel == clrTransparent) { ::SetPixel(hAndMaskDC,x,y,RGB(255,255,255)); ::SetPixel(hXorMaskDC,x,y,RGB(0,0,0)); } else { ::SetPixel(hAndMaskDC,x,y,RGB(0,0,0)); ::SetPixel(hXorMaskDC,x,y,MainBitPixel); } } } ::SelectObject(hMainDC,hOldMainBitmap); ::SelectObject(hAndMaskDC,hOldAndMaskBitmap); ::SelectObject(hXorMaskDC,hOldXorMaskBitmap); ::DeleteDC(hXorMaskDC); ::DeleteDC(hAndMaskDC); ::DeleteDC(hMainDC); ::ReleaseDC(NULL,hDC); } HCURSOR CreateCursorFromBitmap(HBITMAP hSourceBitmap, COLORREF clrTransparent, DWORD xHotspot,DWORD yHotspot) { HCURSOR hRetCursor = NULL; do { if(NULL == hSourceBitmap) { break; } //Create the AND and XOR masks for the bitmap HBITMAP hAndMask = NULL; HBITMAP hXorMask = NULL; GetMaskBitmaps(hSourceBitmap,clrTransparent,hAndMask,hXorMask); if(NULL == hAndMask || NULL == hXorMask) { break; } //Create the cursor using the masks and the hotspot values provided ICONINFO iconinfo = {0}; iconinfo.fIcon = FALSE; iconinfo.xHotspot = xHotspot; iconinfo.yHotspot = yHotspot; iconinfo.hbmMask = hAndMask; iconinfo.hbmColor = hXorMask; hRetCursor = ::CreateIconIndirect(&iconinfo); } while(0); return hRetCursor; }
测试代码如下:
void CTestDemoDlg::OnMouseMove(UINT nFlags, CPoint point) { if(NULL != m_hNewCursor) { ::SetCursor(m_hNewCursor); } CDialog::OnMouseMove(nFlags, point); } void CTestDemoDlg::OnBnClickedButton2() { CBitmap bmp ; bmp.LoadBitmap(IDB_BITMAP3) ; HBITMAP m_hSourceBitmap = (HBITMAP)bmp ; m_hNewCursor = CreateCursorFromBitmap(m_hSourceBitmap,RGB(0,0,0),0,0); }
掩码的具体说明可以参照http://blog.csdn.net/iamshuke/archive/2010/07/20/5749897.aspx