I am new to MFC and am making a simple program that will continuously update two edit boxes. The edit boxes contain the x and y coordinates of the mouse cursor. The program only starts grabbing the cursor coordinates when the start button is clicked, and it’s supposed to stop when the stop button is clicked. But as soon as I click the start button the entire window freezes.
Here is what I have so far:
//Way up high in the code:
#include <windows.h>
//way down low in the code
void CmfcpixelDlg::OnBnClickedButtonStart()
{
POINT p;
CString x;
CString y;
int px;
int py;
while(stop == false){
GetCursorPos(&p);
px = p.x;
//convert x coordinate to a CString
x.Format(L"%d", px);
//convert y coordinate to a CString
py = p.y;
y.Format(L"%d", py);
m_x.SetWindowTextW(x.GetBuffer());
m_y.SetWindowTextW(y.GetBuffer());
}
}
You’re blocking the event loop. You can’t do a loop that requires user intervention to end in the GUI thread – you need to do it in a separate thread.
In fact, you shouldn’t perform any lengthy operations in the main thread.
Basically, the same thread that is running your loop is the thread that is responsible for displaying and updating the GUI. Because this thread is now waiting for a GUI update to exit the loop and this thread is the same thread that’s supposed to update the GUI, you have a Catch-22, or in programmer speak, a deadlock.
To resolve this, you can split your code off into a new thread, or better yet, design it to eliminate the loop entirely. Your code is fairly simple, and this can be done loop free: