Application without Application.Run()

  • Thread starter Thread starter Marc Ambrosius
  • Start date Start date
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
 
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?).
 
Back
Top