绘图基础--检测在矩形中鼠标点击事件
初始:
鼠标左键单击:
鼠标左键双击:
鼠标左键双击还原:
// getclcks.cpp
#include <afxwin.h>
// Define the application class
class CApp : public CWinApp
{
public:
virtual BOOL InitInstance();
};
CApp App;
// define the window class
class CWindow : public CFrameWnd
{
BOOL clicked;
BOOL dblClicked;
CRect rect;
public:
CWindow();
virtual ~CWindow();
afx_msg void OnPaint();
afx_msg void OnLButtonUp(UINT, CPoint);
afx_msg void OnLButtonDblClk(UINT, CPoint);
DECLARE_MESSAGE_MAP()
};
// The window's constructor
CWindow::CWindow(): rect(10,10,100,100)
{
clicked=FALSE;
dblClicked=FALSE;
Create(NULL, "Drawing Tests",
WS_OVERLAPPEDWINDOW,
CRect(0,0,200,150));
}
// The message map
BEGIN_MESSAGE_MAP( CWindow, CFrameWnd )
ON_WM_PAINT()
ON_WM_LBUTTONUP()
ON_WM_LBUTTONDBLCLK()
END_MESSAGE_MAP()
// Handle single clicks
void CWindow::OnLButtonUp(UINT flag, CPoint pos)
{
if (rect.PtInRect(pos))
{
clicked=!clicked;
Invalidate(TRUE);
}
}
// Handle double clicks
void CWindow::OnLButtonDblClk(UINT flag,
CPoint pos)
{
if (rect.PtInRect(pos))
{
dblClicked=!dblClicked;
Invalidate(TRUE);
}
}
// Handle exposure
void CWindow::OnPaint()
{
CPaintDC dc(this);
CPen pen(PS_SOLID, 2, RGB(0,0,255)), *oldPen;
CBrush brush(RGB(rand()%256,rand()%256,rand()%256)), *oldBrush; //随机色
if (clicked)
oldPen = dc.SelectObject(&pen);
if (dblClicked)
oldBrush = dc.SelectObject(&brush);
dc.Rectangle(rect);
if (clicked)
dc.SelectObject(oldPen);
if (dblClicked)
dc.SelectObject(oldBrush);
}
// The window's destructor
CWindow::~CWindow()
{
}
// Init the application
BOOL CApp::InitInstance()
{
m_pMainWnd = new CWindow();
m_pMainWnd->ShowWindow(m_nCmdShow);
m_pMainWnd->UpdateWindow();
return TRUE;
}