繪圖基礎--檢測在矩形中鼠標點擊事件

繪圖基礎--檢測在矩形中鼠標點擊事件

初始:



鼠標左鍵單擊:


鼠標左鍵雙擊:


鼠標左鍵雙擊還原:


// 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;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章