右键单击事件,我需要获取作为发件人而不是上下文菜单项右键单击的实际组件



>我正在PictureBox上应用右键单击选项以从虚拟文件夹中删除该图片尝试以下代码:

    main()
    {
        //Some where in main()
        PictureBox pb = new PictureBox();
        pb.ContextMenu = contextMenu_pictureBoxRightClick;
    }
    private void menuItem1_Click(object sender, EventArgs e)
    {
        //Here sender is actual the menuItem which is clicked after right Clicking the picture
        PictureBox pb = (PictureBox)sender;
        // Doing somthing to PictureBox!!! 
    }

但收到错误转换,因为发件人是实际的上下文菜单项

您可以通过以下方式获得从ContextMenuItem右键单击的实际组件(在本例中为PictureBox):

var menuItem = (MenuItem)sender;
var ctxMenu = (ContextMenu)menuItem.Parent;
var actualComponent = (PictureBox)ctxMenu.SourceControl;
//or in short
var actualComponent = (PictureBox)((ContextMenu)((MenuItem)o).Parent).SourceControl;

此代码失败,因为sender表示发生事件的对象。 在这种情况下,它是菜单项而不是PictureBox

听起来您想在单击特定菜单项时访问PictureBox值。 如果是这种情况,那么最好的方法是将PictureBox值设置为字段并直接从单击处理程序访问它

PictureBox pb;
main() {
  ...
  pb = new PictureBox();
  pb.ContextMenu = contextMenu_pictureBoxRightClick;
}
private void menuItem1_Click(object sender, EventArgs e) {
  // pb can be used directly here 
}

最新更新