开发者

Get the SourceControl of my ContextMenuStrip when I use the shortcut key

I have single ContextMenuStrip attached to two controls (DataGridView).

In the ToolStripMenuItem click event, I manage to get the original caller 开发者_如何学JAVA(the DataGridView) with this code :

var menu = (ToolStripDropDownItem)sender;
var strip = (ContextMenuStrip)menu.Owner;
var dgv = (DataGridView)strip.SourceControl;  

It works pretty good when I click on my ToolStripMenuItem.

But when I use the sortcut key linked to the ToolStripMenuItem, the strip.SourceControl return null.

Does anyone know why ?


The SourceControl property shows the control that caused the ContextMenuStrip to open. Since in this case the ContextMenuStrip doesn't display there is no control used to open it, and thus the property is null.

This property is better used in the context of the opening event. See ContextMenuStrip.SourceControl.

Update: One method to figure out which DataGridView was the intended receiver of the ToolStripMenuItem click would be to see which one has the focus:

var dgv = this.ActiveControl as DataGridView;
if ( dgv != null) // make sure to check for null before trying to use this var
    //...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜