Use the ActiveControl property in C#

[ActiveControl]

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 Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in controls and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *