ContextMenuStrip.SourceControl 属性

定义

获取上一个使此 ContextMenuStrip 被显示的控件。

C#
[System.ComponentModel.Browsable(false)]
public System.Windows.Forms.Control SourceControl { get; }
C#
[System.ComponentModel.Browsable(false)]
public System.Windows.Forms.Control? SourceControl { get; }

属性值

使此 ContextMenuStrip 被显示的控件。

属性

示例

下面的代码示例演示了对事件的重用和处理的Opening动态SourceControl确定。 此示例是为 类提供的更大示例的 ContextMenuStrip 一部分。

C#
// This event handler is invoked when the ContextMenuStrip
// control's Opening event is raised. It demonstrates
// dynamic item addition and dynamic SourceControl 
// determination with reuse.
void cms_Opening(object sender, System.ComponentModel.CancelEventArgs e)
{
    // Acquire references to the owning control and item.
    Control c = fruitContextMenuStrip.SourceControl as Control;
    ToolStripDropDownItem tsi = fruitContextMenuStrip.OwnerItem as ToolStripDropDownItem;

    // Clear the ContextMenuStrip control's Items collection.
    fruitContextMenuStrip.Items.Clear();

    // Check the source control first.
    if (c != null)
    {
        // Add custom item (Form)
        fruitContextMenuStrip.Items.Add("Source: " + c.GetType().ToString());
    }
    else if (tsi != null)
    {
        // Add custom item (ToolStripDropDownButton or ToolStripMenuItem)
        fruitContextMenuStrip.Items.Add("Source: " + tsi.GetType().ToString());
    }

    // Populate the ContextMenuStrip control with its default items.
    fruitContextMenuStrip.Items.Add("-");
    fruitContextMenuStrip.Items.Add("Apples");
    fruitContextMenuStrip.Items.Add("Oranges");
    fruitContextMenuStrip.Items.Add("Pears");

    // Set Cancel to false. 
    // It is optimized to true based on empty entry.
    e.Cancel = false;
}

注解

属性的 SourceControl 常见用途包括:

  • 在事件期间 Opening 添加、删除、启用或禁用菜单项。

  • 基于上次显示 ContextMenuStrip的 控件,决定修改所选命令。

适用于

产品 版本
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10