1. 程式人生 > >09 滑鼠訊息

09 滑鼠訊息

Windows滑鼠訊息
windows有20多種不同的訊息用來報告與滑鼠有關的輸入事件,這些訊息分為視窗客戶區訊息和非視窗客戶區訊息,通常我們只關心客戶區訊息。常見的滑鼠訊息有如下幾種:
WM_MOUSEMOVE
WM_LBUTTONDOWN
WM_LBUTTONUP
WM_LBUTTONDBLCLK
WM_RBUTTONDOWN
WM_RBUTTONUP
WM_RBUTTONDBLCLK
WM_MBUTTONDOWN
WM_MBUTTONUP
WM_MBUTTONDBLCLK
其中L代表Left, R代表Right, M代表Middle,通過名字我們就能知道它們的用途。下面我們通過一個小小示例來演示用法:
按下左鍵並移動,釋放的時候畫線
在這裡插入圖片描述


按下Ctrl+左鍵並移動,釋放的時候畫矩形
在這裡插入圖片描述
按下右鍵並移動塗鴉
在這裡插入圖片描述
程式碼如下:

/*
 *HelloMFC.h
 */
#ifndef _HELLO_MFC_
#define _HELLO_MFC_

class CMyApp : public CWinApp{
public:
	virtual BOOL InitInstance();
};

class CMainWindow : public CFrameWnd{
public:
	CMainWindow();
	afx_msg void OnPaint();
	afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
	afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
	afx_msg void OnMouseMove(UINT nFlags, CPoint point);
	afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
	afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
	DECLARE_MESSAGE_MAP()
	CPoint m_ptFrom;
};

#endif

/*
 *HelloMFC.cpp
 */
#include <afxwin.h>
#include "HelloMFC.h"

CMyApp myApp;

BOOL CMyApp::InitInstance()
{
	m_pMainWnd = new CMainWindow;
	m_pMainWnd->ShowWindow(m_nCmdShow);
	m_pMainWnd->UpdateWindow();

	return TRUE;
}

BEGIN_MESSAGE_MAP(CMainWindow, CFrameWnd)
	ON_WM_PAINT()
	ON_WM_LBUTTONDOWN()
	ON_WM_LBUTTONUP()
	ON_WM_MOUSEMOVE()
	ON_WM_RBUTTONDOWN()
	ON_WM_RBUTTONUP()
END_MESSAGE_MAP()			  


CMainWindow::CMainWindow()
{
	Create(NULL, TEXT("塗鴉板"));
}

void CMainWindow::OnLButtonDown(UINT nFlags, CPoint point)
{
	m_ptFrom = point;
	SetCapture();
}

void CMainWindow::OnLButtonUp(UINT nFlags, CPoint point)
{
	CPen pen;
	CClientDC dc(this);
	pen.CreatePen(PS_SOLID, 5, RGB(255, 0 ,0));
	dc.SelectObject(&pen);
	if (!(nFlags & MK_CONTROL)){
		dc.MoveTo(m_ptFrom);
		dc.LineTo(point);
	}
	ReleaseCapture();
}

void CMainWindow::OnRButtonDown(UINT nFlags, CPoint point)
{
	m_ptFrom = point;
	SetCapture();
}

void CMainWindow::OnRButtonUp(UINT nFlags, CPoint point)
{
	ReleaseCapture();
}

void CMainWindow::OnMouseMove(UINT nFlags, CPoint point)
{
	if (nFlags & MK_LBUTTON && !(nFlags & MK_CONTROL)){//滑鼠左鍵按下且移動
		CClientDC dc(this);
		dc.MoveTo(m_ptFrom);
		dc.LineTo(point);
		dc.SetROP2(R2_NOT);
		dc.MoveTo(m_ptFrom);
		dc.LineTo(point);
	}	
	if (nFlags & MK_RBUTTON){//滑鼠右鍵按下且移動
		CPen pen;
		pen.CreatePen(PS_SOLID, 5, RGB(255, 158, 53));
		CClientDC dc(this);
		dc.SelectObject(&pen);
		dc.MoveTo(m_ptFrom);
		dc.LineTo(point);
		m_ptFrom = point;
	}
	if (nFlags & MK_LBUTTON && nFlags & MK_CONTROL){//按下Ctrl鍵和左鍵且移動
		CClientDC dc(this);
		dc.Rectangle(m_ptFrom.x, m_ptFrom.y, point.x, point.y);
		dc.Rectangle(m_ptFrom.x, m_ptFrom.y, point.x, point.y);
	}
	
}

void CMainWindow::OnPaint()
{
	
}