Hi. Im a novice to MFC programming. And I was just writing some simple tic tac toe program. My codes are shown below. It only draws X in a square where "l button down" messages occur. But mysteriously it fails to draw Xs in all the squares. If I click in all the squares, it only draws Xs for like 3 or 4 times. After that it stops working even though I click on a square. No errors. No beep message beep sounds. It just stops. But I cant understand where the error is.
Heres my code in header file.
<blockquote class="quote"><div class="op">Quote:</div>
class MainWindow : public CFrameWnd
{
public:
MainWindow()
{
Create(NULL, L"WINDOW");
}
protected:
afx_msg void OnPaint();
afx_msg void OnLButtonDown(UINT, CPoint);
private:
void DrawGrid(CDC*);
void DrawO(CDC*, int);
void DrawX(CDC*, int);
DECLARE_MESSAGE_MAP()
};
class App : public CWinApp
{
public:
BOOL InitInstance()
{
m_pMainWnd = new MainWindow;
m_pMainWnd->ShowWindow(m_nCmdShow);
m_pMainWnd->UpdateWindow();
CRect rec(0, 0, 300, 300);
m_pMainWnd->CalcWindowRect(rec);
m_pMainWnd->SetWindowPos(NULL, 0, 0, rec.Width(), rec.Height(), SWP_NOZORDER | SWP_NOMOVE | SWP_NOREDRAW);
return TRUE;
}
};</blockquote>
And here is the cpp file.
#include "stdafx.h"
#include "MFCApplication15.h"
#define O 1
#define X 2
CRect sqs[9] =
{
{ 0, 0, 100, 100 },
{ 100, 0, 200, 100 },
{ 200, 0, 300, 100 },
{ 0, 100, 100, 200 },
{ 100, 100, 200, 200 },
{ 200, 100, 300, 200 },
{ 0, 200, 100, 300 },
{ 100, 200, 200, 300 },
{ 200, 200, 300, 300 }
};
int vals[9]{0, 0, 0, 0, 0, 0, 0, 0, 0};
void MainWindow::OnPaint()
{
CClientDC dc(this);
DrawGrid(&dc);
for (int i{}; i < 9; i++)
if (vals[i] == X)
DrawX(&dc, i);
}
void MainWindow::OnLButtonDown(UINT flags, CPoint cp)
{
for (int i{}; i < 9; i++)
{
if (PtInRect(sqs[i], cp))
vals[i] = X;
}
}
void MainWindow::DrawGrid(CDC* pDC)
{
CPen *pen = new CPen(PS_SOLID, 5, RGB(0, 0, 0));
pDC->SelectObject(pen);
pDC->MoveTo(0, 100);
pDC->LineTo(300, 100);
pDC->MoveTo(0, 200);
pDC->LineTo(300, 200);
pDC->MoveTo(100, 0);
pDC->LineTo(100, 300);
pDC->MoveTo(200, 0);
pDC->LineTo(200, 300);
}
void MainWindow::DrawO(CDC* pDC, int pos) {
CPen* pen = new CPen(PS_SOLID, 3, RGB(255, 0, 0));
pDC->SelectObject(pen);
pDC->Ellipse(sqs[pos]);
}
void MainWindow::DrawX(CDC* pDC, int pos)
{
CPen* pen = new CPen(PS_SOLID, 3, RGB(0, 0, 255));
pDC->SelectObject(pen);
pDC->MoveTo(sqs[pos].left, sqs[pos].top);
pDC->LineTo(sqs[pos].right, sqs[pos].bottom);
pDC->MoveTo(sqs[pos].right, sqs[pos].top);
pDC->LineTo(sqs[pos].left, sqs[pos].bottom);
}
App myApp;
BEGIN_MESSAGE_MAP(MainWindow, CFrameWnd)
ON_WM_PAINT()
ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()
What's the wrong with my code ? Why it stops the drawing after like 4 clicks ?
Thanks in advance.