我在处理动态对象上的鼠标单击事件时遇到问题。 我有 2 个表单,一个名为“FormMain”的主表单和另一个名为“FormView”的自定义表单, 我创建一个基于 PictureBox 类的组件,如下所示:
public class customPB : PictureBox
{
public customPB()
{
InitializeComponent();
this.Width = 195;
this.Height = 114;
this.Visible = true;
this.Invalidate();
}
.
.
private void BtnLink_Click(object sender, MouseEventArgs e)
{
MessageBox.Show("Button Click Event");
}
.
.
private void InitializeComponent()
{
this.btnAmazon = new Button();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
this.SuspendLayout();
//
// btnLink
//
this.btnLink.BackColor = System.Drawing.Color.White;
this.btnLink.BackgroundImage = Properties.Resources.LinkIcon;
this.btnLink.Location = new System.Drawing.Point(9, 70);
this.btnLink.Name = "btnLink";
this.btnLink.Size = new System.Drawing.Size(34, 34);
this.btnLink.TabIndex = 1;
this.btnLink.MouseClick += new MouseEventHandler(BtnLink_Click);
this.Controls.Add(this.btnLink);
this.Size = new System.Drawing.Size(195, 114);
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
this.ResumeLayout(false);
}
}
在我的项目中,我创建了这样的“FormView”表单:
class FormView : Form
{
public FormView(Form windowParent, Point windowPosition ,Size windowSize )
{
_windowPosition = windowPosition;
this.Owner=windowParent;
InitializeComponent();
windowParent.LocationChanged += FormView_LocationChanged;
this.Location = windowParent.PointToScreen(windowPosition);
this.ClientSize = windowSize;
this.Show(windowParent);
}
private void FormView_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
custPB = new customPB();
this.Controls.Add(custPB);
}
}
private void InitializeComponent()
{
this.SuspendLayout();
this.ClientSize = new System.Drawing.Size(284, 261);
this.Name = "OverlayWindow";
this.DoubleBuffered = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowIcon = false;
this.ControlBox = false;
this.ShowInTaskbar = false;
this.Paint += FormView_Paint;
this.MouseDoubleClick += FormView_MouseDoubleClick;
this.ResumeLayout(false);
}
protected override void OnActivated(EventArgs e)
{
// Always keep the owner activated instead
this.BeginInvoke(new Action(() => this.Owner.Activate()));
}
}
在主窗体中我创建新的“FormView”,如下所示:
private FormView frm1 ;
public frmMain()
{
InitializeComponent();
FormView frm1 = new FormView(this);
FormView.Visible = true;
}
当我单击自定义图片框组件中的 btnLink 时,没有发生任何事情,我的错误是什么? 谢谢
尝试在动态创建的自定义组件中触发按钮上的单击事件
您必须删除事件处理程序:
protected override void OnActivated(EventArgs e)
{
// Always keep the owner activated instead
this.BeginInvoke(new Action(() => this.Owner.Activate()));
}
通过调用 this.Owner.Activate(),您将焦点授予父表单,而 customPB 失去焦点,从而阻止单击事件正常工作。