The following function is intended to be called in response to a mouse button-down message, such as WM_LBUTTONDOWN. The function determines whether the user has clicked within the bounding rectangle of the image. If the user has clicked, the function captures the mouse input, erases the image from the client area, and calculates the position for the hot spot within the image. The function sets the hot spot to coincide with the hot spot of the mouse cursor. Then the function begins the drag operation by calling ImageList_BeginDrag.
// StartDragging - begins dragging a bitmap.
// Returns TRUE if successful or FALSE otherwise.
// hwnd - handle of the window in which the bitmap is dragged
// ptCur - coordinates of the cursor
// himl - handle of the image list
//
// Global variables
// g_rcImage - bounding rectangle of the image to drag
// g_nImage - index of the image
// g_ptHotSpot - location of the image's hot spot
// g_cxBorder and g_cyBorder - width and height of border
// g_cyCaption and g_cyMenu - height of title bar and menu bar
extern RECT g_rcImage;
extern int g_nImage;
extern POINT g_ptHotSpot;
BOOL StartDragging(HWND hwnd, POINT ptCur, HIMAGELIST himl)
{
// Return if the cursor is not in the bounding rectangle of
// the image.
if (!PtInRect(&g_rcImage, ptCur))
return FALSE;
// Capture the mouse input.
SetCapture(hwnd);
// Erase the image from the client area.
InvalidateRect(hwnd, &g_rcImage, TRUE);
UpdateWindow(hwnd);
// Calculate the location of the hot spot, and save it.
g_ptHotSpot.x = ptCur.x - g_rcImage.left;
g_ptHotSpot.y = ptCur.y - g_rcImage.top;
// Begin the drag operation.
if (!ImageList_BeginDrag(himl, g_nImage,
g_ptHotSpot.x, g_ptHotSpot.y))
return FALSE;
// Set the initial location of the image, and make it visible.
// Because the ImageList_DragEnter function expects coordinates to
// be relative to the upper-left corner of the given window, the
// width of the border, title bar, and menu bar need to be taken
// into account.
ImageList_DragEnter(hwnd, ptCur.x + g_cxBorder,
ptCur.y + g_cyBorder + g_cyCaption + g_cyMenu);
g_fDragging = TRUE;
return TRUE;
}