MessageBox Problem

Jun 2, 2012 at 1:17pm
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 Jun 2, 2012 at 1:18pm
Jun 2, 2012 at 2:40pm
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
Jun 2, 2012 at 4:23pm
But it doesn't work when I change ESC to other key.
Jun 2, 2012 at 6:38pm
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 Jun 2, 2012 at 6:38pm
Jun 3, 2012 at 6:19am
GetAsyncKeyState function can't work either.
Jun 3, 2012 at 2:52pm
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 Jun 3, 2012 at 2:59pm
Jun 4, 2012 at 4:04am
If I want to press ESC to break,can I not use MessageBox?
Jun 5, 2012 at 12:41pm
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.
Jun 5, 2012 at 2:19pm
Thanks!
Topic archived. No new replies allowed.