4

C#: 2 つの異なるオブジェクトにリンクされているときに、コンテキスト メニューのメニュー項目の呼び出し元を検出する方法は?

lblOn と lblOff という 2 つのラベルがあります。「1つの」コンテキストメニューを両方のラベルにリンクして、同じものを2つ作成する必要がないようにしています。

contextmenu.menuitem と呼ばれるラベル オブジェクトを見つけるにはどうすればよいですか? そのようにして、クリックされたメニューアイテムは、コンテキストメニューが lblOn ラベルまたは lblOffline によって呼び出されたかどうかを認識しますか?

4

4 に答える 4

16

SourceControlのプロパティを確認しますContextMenuStrip

于 2009-06-10T11:30:30.940 に答える
6

無視。もう少しグーグルで調べたところ、解決策とコード例が見つかりました。

private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
    //Make sure the sender is a ToolStripMenuItem
    ToolStripMenuItem myItem = sender as ToolStripMenuItem;
    if (myItem != null)
    {
        //Get the ContextMenuString (owner of the ToolsStripMenuItem)
        ContextMenuStrip theStrip = myItem.Owner as ContextMenuStrip;
        if (theStrip != null)
        {
            //The SourceControl is the control that opened the contextmenustrip.
            //In my case it could be a linkLabel
            LinkLabel linkLabel = theStrip.SourceControl as LinkLabel;
            if (linkLabel == null)
                MessageBox.Show("Invalid item selected.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            else
            {
                if (MessageBox.Show(string.Format("Are you sure you want to remove BOL {0} from this Job?", linkLabel.Text), "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    linkLabel.Text = Program.NullValue(linkLabel);
                }
            }
        }
    }
}

ソース: http://www.tek-tips.com/viewthread.cfm?qid=1441041&page=8

于 2009-06-10T11:48:48.877 に答える
2

これは何ヶ月も前からの質問であることは知っていますが、コードで簡単な答えを見つけることができませんでした... SLaksが指摘したことは知っていますが、コードサンプルが必要な人もいると思います...

リッチ テキスト ボックスまたはラベルの間のコンテキスト メニューを呼び出したのは誰かを知りたかったのです。その理由は、コンテキスト メニューが 1 つだけ必要であり、呼び出し元が何も選択されていないリッチ テキスト ボックスである場合、そのメニュー内のコピー ボタンを無効にしたかったからです。

私のコードは次のとおりです。

    private void contextMenuStrip1_Opened(object sender, EventArgs e)
    {
        //get the context menu (it holds the caller)
        ContextMenuStrip contextMenu = sender as ContextMenuStrip;
        //get the callers name for testing 
        string controlName = contextMenu.SourceControl.Name;

        //test if it is infact me rich text editor making the call.
        if (controlName == "text_rchtxt")
        {
            //if I have nothing selected... I should not be able to copy
            if (text_rchtxt.SelectedText == "")
                copy_shrtct.Enabled = false; 
        }
        else
        {
            //if I do have something selected or if its another control making the call, enable copying
            copy_shrtct.Enabled = true;
        }
    }
于 2012-09-14T21:20:55.747 に答える
-1

これを使って:

contextMenuStrip1.SourceControl;
于 2015-09-30T06:18:45.693 に答える