我有一个自定义控件,我试图将System.Windows.Forms.Button显示在上面。
这是On paint事件。这会被调用,消息框显示正确的值。位置是1,1。大小为75,23,可见。
public partial class CustomControl : Control
{
public CustomControl()
{
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics graphics = e.Graphics;
Rectangle rect = e.ClipRectangle;
// Other code here.
OptionsBtn.Refresh(); // I tried Invalidate and Update. Neither of them worked.
//MessageBox.Show(OptionsBtn.Location.ToString() + "\n" + OptionsBtn.Size.ToString() + "\n" + OptionsBtn.Visible.ToString());
}
}
这是组件的初始化。
partial class CustomControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.OptionsBtn = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// OptionsBtn
//
this.OptionsBtn.BackColor = System.Drawing.Color.Blue;
this.OptionsBtn.ForeColor = System.Drawing.Color.Red;
this.OptionsBtn.Location = new System.Drawing.Point(1, 1);
this.OptionsBtn.Name = "Options";
this.OptionsBtn.Size = new System.Drawing.Size(75, 23);
this.OptionsBtn.TabIndex = 0;
this.OptionsBtn.Text = "Options";
this.OptionsBtn.UseVisualStyleBackColor = false;
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button OptionsBtn;
}
答案 0 :(得分:1)
您的代码的主要问题是,虽然您创建了OptionBtn
按钮,但您从未将其添加到CustomControl
。
private void InitializeComponent()
{
this.OptionsBtn = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// OptionsBtn
//
this.OptionsBtn.BackColor = System.Drawing.Color.Blue;
this.OptionsBtn.ForeColor = System.Drawing.Color.Red;
this.OptionsBtn.Location = new System.Drawing.Point(1, 1);
this.OptionsBtn.Name = "Options";
this.OptionsBtn.Size = new System.Drawing.Size(75, 23);
this.OptionsBtn.TabIndex = 0;
this.OptionsBtn.Text = "Options";
this.OptionsBtn.UseVisualStyleBackColor = false;
this.Controls.Add(this.OptionsBtn);
this.ResumeLayout(false);
}
我已添加此行:
this.Controls.Add(this.OptionsBtn);
只有这个按钮才属于CustomControl
。
然后,您必须将CustomControl
添加到某些Form
。类似的东西(假设你在代码中也需要这个位):
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
CustomControl cc = new CustomControl();
cc.Location = new Point(100, 100);
cc.Size = new Size(300, 300);
this.Controls.Add(cc);
}
}