【发布时间】:2021-11-29 14:07:25
【问题描述】:
在 C# Forms 中,我可以轻松地在设计模式下添加 PictureBox,然后双击 MouseHover 和 MouseLeave 事件并将背景颜色更改为红色和蓝色等。我看到在“Form1Designer.cs”选项卡中填充了以下代码:
this.pictureBox1 = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// pictureBox1
//
this.pictureBox1.Location = new System.Drawing.Point(203, 56);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(417, 273);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
this.pictureBox1.MouseLeave += new System.EventHandler(this.pictureBox1_MouseLeave);
this.pictureBox1.MouseHover += new System.EventHandler(this.pictureBox1_MouseHover);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.pictureBox1);
this.Name = "Form1Hover";
this.Text = "Form1Hover";
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
但是,我应该在运行时执行此操作,因此当有人查看设计表单时,它不应该在其中显示任何图片框。如果我打开一个新表单并将上面的代码复制并粘贴到“Form1Designer.cs”选项卡中,那么所有代码都会以红色错误突出显示。所以我不能让它在这里工作。
通过执行以下代码,我能够成功完成运行时图片框编码。 在“Form1Designer.cs”选项卡中,我只添加了:
this.Controls.Add(this.pictureBox1);
在“Form1.cs”标签中我添加了:
public partial class Form1 : Form
{
PictureBox pictureBox1 = new PictureBox(); // got instance of Picture Box here
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.MouseHover += new EventHandler(this.pictureBox1_MouseHover);
pictureBox1.MouseLeave += new EventHandler(this.pictureBox1_MouseLeave);
}
private void pictureBox1_MouseHover(object sender, EventArgs e)
{
pictureBox1.BackColor = Color.Blue;
}
private void pictureBox1_MouseLeave(object sender, EventArgs e)
{
pictureBox1.BackColor = Color.Red;
}
}
我有两个问题,
问题1:我想不可能在Form1Designer.cs中编写所有代码来生成图片框及其事件,对吗?
问题 2:我的解决方案要求我在最外层范围内获取“Form1.cs”中的图片框实例 {};换句话说,尽可能全球化。我觉得这不是一个非常干净的方法来获取图片框的实例,我的 Form1 会很混乱。有没有更好的办法?
提前致谢
【问题讨论】:
-
也许您错过了设计器生成的代码中定义了
pictureBox1变量的行?例如。private System.Windows.Forms.PictureBox picureBox1;?也许这就是为什么所有的线都变成红色的:) -
Form1.Designer 是一个生成的文件,如果您在设计器视图中更改某些内容,您将丢失其中的所有自定义代码。此外,Form1.Designer.cs 和 Form1.cs 是部分类。如果在 Form1.cs 而不是 Form1.Designer.cs 中声明图片框,它不会“变得更加全局”,因为它在不同文件中是同一个类。
标签: c# controls runtime picturebox