MessageBox Problem

My program is a console application.
I want to break when ESC is pressed, but it can't work when I debug it at VS2010.
If I delete the sentence which have MessageBox, it could work.
What's the reason ?
Thanks for the help in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <Windows.h>
using namespace std;

int main()
{
	MessageBox(GetConsoleWindow(),TEXT("Press ESC to break!"),TEXT("info"),MB_OK | MB_ICONINFORMATION);
	while(true)
	{
		if((GetKeyState(27) & 0x80) == 0x80)
			break;
	}
	cout<<"have breaked!"<<endl;
	system("pause");
	return 0;
}
Last edited on
If a message box has a Cancel button, the function returns the IDCANCEL value if either the ESC key is pressed or the Cancel button is selected. If the message box has no Cancel button, pressing ESC has no effect.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms645505%28v=vs.85%29.aspx
But it doesn't work when I change ESC to other key.
Try this instead:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <Windows.h>
using namespace std;

int main()
{
	MessageBox(GetConsoleWindow(),TEXT("Press ESC to break!"),TEXT("info"),MB_OK | MB_ICONINFORMATION);
	while(true)
	{
		//Note the use of GetAsyncKeyState function
        //and also the test  with 0x8000
      //
        if((GetAsyncKeyState(27) & 0x8000) == 0x8000)  //test for escape key
			break;
	}
	cout<<"have breaked!"<<endl;
	system("pause");
	return 0;
}
Last edited on
GetAsyncKeyState function can't work either.
MessageBox is a Blocking Function - Unless you specify a Parent Window. It will NOT return until you press a button.
So, first you click a button, THEN it will check for a keypress.
Last edited on
If I want to press ESC to break,can I not use MessageBox?
Not if you want to close your MessageBox. You cannot close a MessageBox unless you know its Window Handle (HWND). You only can ask a user input to close it. But you can create your own MessageBox-ish function that creates a new MessageBox and returns also a HWND so you can close it.
Thanks!
Topic archived. No new replies allowed.