Can't get ComboBox to show that it has focus

T

TOANDO

I have a WinForm with many text boxes and several combo boxes. I also
have a toolstrip with cut, copy, and paste icons. When a user clicks
one of the buttons (cut/copy/paste), I want to get the current active
control and if it is a textbox or a combobox, to then copy the
selected text to the clipboard (or do the appropriate option based on
the button). I can get all of this to work just fine with the
textboxes. To figure out the active control, I am using the
GetFocus() pointer from "user32.dll". This is the only way I could
find to do what I needed to do. Below is an example of how my code
looks.
[DllImport("user32.dll")]
public static extern IntPtr GetFocus();

private void btnCopy_Click(object sender, EventArgs e)
{
FocusControl = Control.FromHandle(GetFocus());

if (FocusControl != null)
{
if (FocusControl.GetType().ToString() ==
"System.Windows.Forms.TextBox")
{
TextBox myTextBox = (TextBox)FocusControl;
if (!string.IsNullOrEmpty(myTextBox.SelectedText))
{
Clipboard.SetText(myTextBox.SelectedText);
}
}
else if (FocusControl.GetType().ToString() ==
"System.Windows.Forms.ComboBox")
{
ComboBox myComboBox = (ComboBox)FocusControl;
Clipboard.SetText(myComboBox.SelectedText);
}
}
}

This works great for textboxes, but if the focus is on a combobox, the
FocusControl object is null, so it doesn't fall into the if
statement. I've tried using the ActiveControl method, but couldn't
figure out how to drill down to the actual control that had focus.
All it gave me back was the control that the textbox was on, not the
actual textbox control. I'm sure I could iterate through each child
control, but I figured there had to be an easier way. Any help would
be greatly appreciated.
 
K

Kevin Spencer

Hi TOANDO,

The GetFocus() API function returns a handle to the window that has the
KEYBOARD focus.

All you really have to do is to create a field in your Form class that
references a Control. For the Controls that you want to copy from, implement
a Focus event handler that sets the value of the field to that Control. Your
Form will then know at all times which of them has the Focus (if any).

--
HTH,

Kevin Spencer
Chicken Salad Surgeon
Microsoft MVP
 

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