I'm trying to implement a cut/copy/paste menu into our application and I'm having trouble trying to determine what the current control that has focus. // Obtain a handle to the control that currently has focus
I've done all the 'hard' bits by making the application clipboard aware (WM_DRAWCLIPBOARD) and have full capability for custom clipboard data etc. but I just cannot get the last piece of the puzzle to work! The application is built up from extensible components. I'm trying to provide a means for all 'clipboard aware' controls (textbox, combo, etc.) in the application to have it 'for free'. i.e. I don't want to mandate a custom textbox instead of the WinForms one (some of the application extensions may be 3rd party for example).
In my form's WndProc (C# form overriden method) I've been trapping the WM_PARENTNOTIFY message and then calling GetFocus() and then Control.FromChildHandle() to obtain what I thought would be the active control. However I notice that GetFocus() is returning a handle to the previous control. If I click on the control again the Control is returned as the one I think it is. If I click off the control on to another then it's the same 1st event is the old control and the 2nd time I click it's the 'new' control.
Here's a few snippets of code:
case WM_PARENTNOTIFY:
if( (int) m.WParam == WM_LBUTTONDOWN )
{
// Attempt to update the menu state
ConfigureMenu();
}
//---
Control ctlFocus = GetControlWithFocus();
TextBoxBase textBox = ctlFocus as TextBoxBase;
if( textBox != null )
{
// It's a textbox so basic text paste is possible, check that the clipboard has text data...
}
//---
Control controlWithFocus = null;
IntPtr handleControl = GetFocus();
if( handleControl != IntPtr.Zero )
{
// Obtain the control fro the handle
controlWithFocus = Control.FromChildHandle( handleControl );
}
return controlWithFocus;
Our custom controls handle the request differently so will always work but I need a solution for the standard .NET Framework controls which have built-in clipboard support (such as anything derived from TextBoxBase).
It's a bit late so perhaps I've missed something obvious but does anyone have any advice Thanks in advance!

Getting reference to control with focus