[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Use the ActiveControl property in C#

[Use the ActiveControl property in C#]

The ActiveControl property gives a reference to a container's currently active control. For a form, ActiveControl doesn't count menus, so a menu item can use ActiveControl to see which control was active when the menu was opened.

In this example, the menu items use ActiveControl to determine whether the currently active control is a TextBox and, if it is, they call that control's Copy, Cut, or Paste methods.

The following code shows the example's menu code.

// Copy from the currently active TextBox. private void mnuEditCopy_Click(object sender, EventArgs e) { if (ActiveControl is TextBox) { TextBox txt = ActiveControl as TextBox; txt.Copy(); } } // Cut from the currently active TextBox. private void mnuEditCut_Click(object sender, EventArgs e) { if (ActiveControl is TextBox) { TextBox txt = ActiveControl as TextBox; txt.Cut(); } } // Cut into the currently active TextBox. private void mnuEditPaste_Click(object sender, EventArgs e) { if (ActiveControl is TextBox) { TextBox txt = ActiveControl as TextBox; txt.Paste(); } }

in each case, the code determines whether the ActiveControl is a TextBox and, if it is, the code calls the appropriate TextBox method. It's as simple as that.

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.