Application without Application.Run()

M

Marc Ambrosius

Hello,

in our current project we wanted to get into the
application's message loop to catch some messages (e.g.
keyboard events for accelerators). We found several
possibilities (hooks and hot keys are global) and finally
ended up with an application without a call to
Application.Run(), see the following example:

static void Main()
{
int i = 0;
mainForm = new MainForm();
mainForm.Visible = true;

MSG msg = new MSG();
System.Exception exception = null;

while (GetMessage(ref msg, 0, 0, 0) == 1)
{
try
{
TranslateMessage(ref msg);
if (msg.message == 0x101)
{
i++;
mainForm.label1.Text = i.ToString();
}
DispatchMessage(ref msg);
}
catch (System.Exception e)
{
exception = e;
}
}
if (exception != null)
{
MessageBox.Show(exception.ToString(), "Exception");
}
}

One just has to make sure that Application.Exit(); is
called finally.

As nobody here really knows what Application.Run() exactly
does I don't feel very comfortable running a program like
this. Does anybody have an idea if we will encounter any
difficulties, or is our approach possible?

Any idea is appriciated

Marc
 
C

Chris Tacke, eMVP

That's basically what Application.Run() does - it just goes into a message
pump that exits when the passed-in Form reference become invalid. Your code
looks fine (though how should the app actually die?).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top