Interop: Windows Message Pump
I have this main method that contains a loop to retrieve the messages from the messageQueue that the main window is running. If a key is released(KEYUP) on the keyboard the message goes to a function wich responds when a certain key is pressed.
If the escape key is released the function post the quit message in the queue (PostQuitMessage(0)).
The problem accures when I close the window by pressed the Close button in the controlbox.
The "while(MessageQueue.GetMessage(out msg ,form.Handle ,0 ,0))" line gets hilited and the error shows.
Cannot access a disposed object named "MainForm"
So I suppose the Form is disposed before I can get any message from the queue that tells that the program has ended.
Even if I nest the while loop in another while loop with form.Created as condition the error shows.
I could nest this loop in a try catch block. But I then I can't debug the application properly.
Is there a way around this problem?
[STAThread]
static void Main()
{
MSG msg = new MSG();
MainForm form = new MainForm();
form.Show();
while(MessageQueue.GetMessage(out msg ,form.Handle ,0 ,0))
{
MessageQueue.TranslateMessage(ref msg);
MessageQueue.DispatchMessage(ref msg);
switch(msg.message)
{
case (uint)WM.KEYUP:
Functions.CheckKey(ref msg);
break;
}
Application.DoEvents();
}
}