R – What’s the equivalent of PostMessage to self, for Windows Forms

.netcontrolswindowswinforms

I'm writing a custom control derived from System.Windows.Forms.Control.

The control is using the Control.KeyDown event, to watch keystrokes: I should handle some keystrokes (for example <Ctrl>-K) as hotkeys, which cause me to launch a dialog box.

If I launch the dialog from my onKeyDown event handler, the dialog is displayed before I set KeyEventArgs.SuppressKeyPress to true and return (and so I'm failing to suppress the K keypress). Instead, I'd like to return from the onKeyDown event handler, and launch the dialog afterwards. To do this, after I return from the onKeyDown event handler I need to be invoked again somehow, with some kind of 'launch the dialog' event.

On Win32, I could generate this event by using the PostMessage API, to send a registered window message to myself: I would receive this message right after any previous message in my message queue, and use it as the signal to launch my dialog. Here however I can't use PostMessage function (nor the WndProc method) because I want to use strictly managed APIs (without needing SecurityPermissionFlag::UnmanagedCode).

So what would be the managed equivalent, for a thread (my UI thread) to schedule an asynchronous callback: perhaps a timer of some kind? Some kind of self-Invoke?

Best Solution

My first thought was "set the SurpressKeyPress property before opening the dialog", but that's not really answering your question. If you really need to return from the event handler before opening the dialog, take a look at the BeginInvoke method.

you could do something like this:

...
this.BeginInvoke(new InvokeDelegate(showDlg));
KeyEventArgs.SuppressKeyPress = true;
...


public void showDlg()
{
   // create and show dialog here
}