我有一个从Forms.Control派生的控件,它可以很好地处理鼠标事件和绘制事件,但我在处理按键事件时遇到了问题。我需要处理向左箭头和向右箭头,但到目前为止,包含我的类的Tab控件接受了它们。
如何使此控件可选择、可聚焦?
发布于 2010-05-04 01:49:46
这是一个制作可聚焦控件的很好的教程。我只是跟踪它以确保它能正常工作。此外,还向控件添加了一个按键事件,该事件在控件具有焦点的条件下工作。
http://en.csharp-online.net/Architecture_and_Design_of_Windows_Forms_Custom_Controls%E2%80%94Creating_a_Focusable_Control
基本上,我所做的就是为我的自定义控件创建一个实例,它继承自control。然后添加了KeyPress、Click和Paint事件。按键只是一条消息:
void CustomControl1_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(string.Format("You pressed {0}", e.KeyChar));
}Click事件只有:
this.Focus();
this.Invalidate();我像这样做的paint事件,只是为了让它可见:
protected override void OnPaint(PaintEventArgs pe)
{
if (ContainsFocus)
pe.Graphics.FillRectangle(Brushes.Azure, this.ClientRectangle);
else
pe.Graphics.FillRectangle(Brushes.Red, this.ClientRectangle);
}然后,在主窗体中,创建一个名为mycustomcontrol的实例并添加事件处理程序后:
mycustomcontrol.Location = new Point(0, 0);
mycustomcontrol.Size = new Size(200, 200);
this.Controls.Add(mycustomcontrol);这个例子比我的五分钟代码要整洁得多,只是想确保用这种方式解决你的问题是可能的。
希望这能对你有所帮助。
发布于 2010-05-04 01:38:05
为了使控件可选,您的控件必须设置ControlStyles.Selectable样式。您可以通过调用SetStyle在构造函数中执行此操作。
发布于 2010-05-04 01:42:28
在看不到你的代码的情况下,我只能告诉你我创建了一个3标签的容器,并创建了一个非常简单的覆盖OnGotFocus的控件:
public partial class CustomControl1 : Control
{
public CustomControl1()
{
InitializeComponent();
}
protected override void OnGotFocus(EventArgs e)
{
this.BackColor = Color.Black;
base.OnGotFocus(e);
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
}我将控件和其他几个按钮放在窗体上,适当地设置了制表位,行为与预期一致。代码中的某些其他默认属性已更改,导致该控件不可选。
https://stackoverflow.com/questions/2759602
复制相似问题