MFC中鼠标消息的处理--WM_LBUTTONDWON,WM_RBUTTONDWON

                                           MFC中鼠标消息的处理 

                                                                                                                                                                                                     Last Edit 2013/10/26

MFC中鼠标消息处理一般有
鼠标双击:        WM_LBUTTONDBLCLK,WM_RBUTTONDBLCLK
鼠标单击:        WM_LBUTTONDOWN,WM_RBUTTONDOWN,
鼠标移动:        WM_MOUSEMOVE
鼠标滚轮滑动:WM_MOUSEWHELL
下面将要在一个SDI做一个简易的五子棋棋盘,并且当在网格中单击左键是下黑子,单击右键时下红子,其他功能没有写,比如悔棋等。下面是效果图

MFC中鼠标消息的处理--WM_LBUTTONDWON,WM_RBUTTONDWON_第1张图片



1.绘制棋盘  

要在客户区空白处画出50*50的小方格,我们就要计算出这个区域能画出多少个这样的格子,为了计算方便,我们的做法是让格子铺满整个区域。下面这个做定义的方法就是实现这个功能。

int nWidth;
int nHeight;


void CGameView::DrawBoard(CDC* pDC)
{
	CRect rect;
	GetClientRect(&rect);
	m_nWidth=rect.Width();
	m_nHeight=rect.Height();

	int xCount=m_nWidth%50;
	int yCount=m_nHeight%50;

	for (int i=0;iMoveTo(i*50,0);
		pDC->LineTo(i*50,m_nHeight);
	}
	
	for (int j=0;jMoveTo(0,j*50);
		pDC->LineTo(m_nWidth,j*50);
	}

}

然后在View中OnDraw中调用该函数,绘出棋盘。

void CGameView::OnDraw(CDC* pDC)
{
	CGameDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);
	if (!pDoc)
		return;
	// TODO: 在此处为本机数据添加绘制代码
	DrawBoard(pDC );	
}
下面为棋盘添加鼠标消息,当单击左键时,下黑子,当单击右键时,下红子。交替落子,同时在以下过的棋盘中不能落子。(以后的想法是,如果能够实现网络对站的话,右键应该为悔棋)。
根据以上的要求:要定义一个指示器
int m_leftOrRight; //是一个指示器,0表示左单击,下黑子,1表示右单击,下红子
定义一个vector向量,用来存储棋盘中每一个方格。在GameView.h的头文件中加入以下代码(注意:在class CGameView : public CView最上面)
#include 
using std::vector;
#pragma once

typedef struct{
	CRect rect;
	int flag;
}GameRect;
在CGameView中定义一个public向量

vector gameRect;
其他的变量如下

int xCount; //最多条竖线
int yCount;  //最多条横线


以上就是整个个程序的变量声明了。

下面要声明几个函数
void DrawBoard(CDC* pDC);
int SaveRect(void);
int GameRun(CBrush* pBrush, CPoint pos);

注意LineTo,MoveTo的使用顺序。
void CGameView::DrawBoard(CDC* pDC)
{
	CRect rect;
	GetClientRect(&rect);
	m_nWidth=rect.Width();
	m_nHeight=rect.Height();
	int xCount=m_nWidth%50;
	int yCount=m_nHeight%50;
	for (int i=0;iMoveTo(i*50,0);
		pDC->LineTo(i*50,m_nHeight);
	}	
	for (int j=0;jMoveTo(0,j*50);
		pDC->LineTo(m_nWidth,j*50);
	}
}
int CGameView::SaveRect(void)
{
	GameRect myRect;
	myRect.flag=0;
	for (int i=0;i

然后在OnDraw中调用这两个函数 
void CGameView::OnDraw(CDC* pDC)
{
	CGameDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);
	if (!pDoc)
		return;
	// TODO: 在此处为本机数据添加绘制代码
	DrawBoard(pDC );
	SaveRect();
}
最后就是分别为其添加WM_LBUTTONDOWN,WM_RBUTTONDWON消息函数
void CGameView::OnLButtonDown(UINT nFlags, CPoint point)
{
	CBrush * pBlackBrush=new CBrush(RGB(0,0,0));
	if (m_leftOrRight==0)
	{
		GameRun(pBlackBrush,point);
		m_leftOrRight=1;
	}
	delete pBlackBrush;
	CView::OnLButtonDown(nFlags, point);
}

void CGameView::OnRButtonDown(UINT nFlags, CPoint point)
{
	// TODO: 在此添加消息处理程序代码和/或调用默认值
	CBrush * pRedBrush=new CBrush(RGB(255,0,0));
	if (m_leftOrRight==1)		
	{	
	GameRun(pRedBrush,point);
	m_leftOrRight=0;
        }
	delete pRedBrush;
	CView::OnRButtonDown(nFlags, point);
}





你可能感兴趣的:(VC/MFC)