C++怎么获取指定窗口句柄某点像素值

2024-12-25 12:41:33
推荐回答(2个)
回答1:

#include 
#include 

typedef CWinTraits FrameWinTraits; 

class CMainFrame : public CWindowImpl {
public:
BEGIN_MSG_MAP(CMainFrame)
MESSAGE_HANDLER(WM_CLOSE, OnClose)
MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBkgnd)
MESSAGE_HANDLER(WM_PAINT, OnPaint)
MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown)
MESSAGE_HANDLER(WM_LBUTTONUP, OnLButtonUp)
MESSAGE_HANDLER(WM_MOUSEMOVE, OnMouseMove)
END_MSG_MAP()
public:
CMainFrame() : m_clr(0xFFFFFF) {} 
private:
LRESULT OnClose(UINT, WPARAM, LPARAM, BOOL&) 
{
PostMessage(WM_QUIT); 
return 0; 
}

LRESULT OnEraseBkgnd(UINT, WPARAM, LPARAM, BOOL&) 
{
return 1; 
}

LRESULT OnPaint(UINT, WPARAM, LPARAM, BOOL&) 
{
RECT rc; 
PAINTSTRUCT ps; 

GetClientRect(&rc); 
HDC hDC = ::BeginPaint(m_hWnd, &ps); 
COLORREF clrOld = ::SetBkColor(hDC, m_clr);
  if(clrOld != CLR_INVALID)
{
ExtTextOut(hDC, 0, 0, ETO_OPAQUE, &rc, NULL, 0, NULL);
DrawText(hDC, _T("按下鼠标左键移动鼠标获取颜色"), -1, &rc, DT_CENTER | DT_VCENTER | DT_WORDBREAK ); 
SetBkColor(hDC, clrOld);
}
::EndPaint(m_hWnd, &ps);
return 0; 
}

LRESULT OnLButtonDown(UINT, WPARAM, LPARAM lParam, BOOL& bHandled)
{
::SetCapture(m_hWnd); 
return 0; 
}

LRESULT OnLButtonUp(UINT, WPARAM, LPARAM, BOOL& bHandled) 
{
::ReleaseCapture(); 
return 0; 
}

LRESULT OnMouseMove(UINT, WPARAM, LPARAM lParam, BOOL& bHandled) {
POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) }; 
ClientToScreen(&pt); 
HWND hWnd = WindowFromPoint(pt); 
if (m_hWnd != hWnd) {
HDC hDC = ::GetWindowDC(hWnd); 
COLORREF clr = GetPixel(hDC, pt.x, pt.y);
::ReleaseDC(hWnd, hDC); 
if (clr != m_clr) {
m_clr = clr; 
InvalidateRect(NULL); 
}
}
return 0; 
}
private:
COLORREF m_clr; 
};

int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
  DefWindowProc(NULL, 0, 0, 0L);
   
  RECT rc = {0,0,200,100};
CMainFrame wndFrame;
wndFrame.Create(NULL,&rc);
wndFrame.CenterWindow();
wndFrame.ShowWindow(SW_SHOW);
 
  MSG msg;
  while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
  }
wndFrame.DestroyWindow();
   return 0;
}


获取颜色部分在OnMouseMove() 方法中


代码 VC8 测试通过, 测试方法:创建一个空工程,然后添加一个CPP, 直接复制代码后编译即可直接运行

回答2:

windows API 句柄。参考windows api函数手册有详解