我不确定我是否完全理解您要完成的工作,但是如果您希望制作一个可以接收鼠标点击但不会“窃取”焦点的控件,这是很有可能的:
public class Box : Control
{
public Box()
{
// Prevent mouse clicks from 'stealing' focus:
TabStop = false;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
DrawText(e.Graphics);
}
// Display control text so we know what the button does:
private void DrawText(Graphics graphics)
{
using (var brush = new SolidBrush(this.ForeColor))
{
graphics.DrawString(
this.Text, this.Font, brush,
new PointF()
{
X = ((float)this.Width / 2f),
Y = (((float)this.Height / 2f) - (this.Font.GetHeight(graphics) / 2f))
},
new StringFormat()
{
Alignment = StringAlignment.Center
});
}
}
}
这个简单的控件将显示为一个矩形,它仍然能够接收鼠标点击和触发点击事件,但不会从表单上的其他控件(也不是表单本身)窃取焦点。
将表单上的透明度键设置为其背景色将使表单的其余部分不可见,因此只有矩形“按钮”可见。这也可以与Opacity 属性结合使用以使显示的内容半透明,但不透明度恰好为零的表单不会与鼠标交互(由 Windows 设计)。
仅仅将表单的TopMost 属性设置为true 可能不足以使窗口保持在所有其他窗口之上。首次创建表单时,您可能需要在表单内进行以下 API 调用(例如,放置在构造函数中,OnLoad 事件,等): p>
SetWindowPos(this.Handle, HWND_TOPMOST, 0, 0, 0, 0, (SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW));
有关此功能的 MSDN 文档可以在 here 找到。
为了进行此调用,您需要将以下 Windows API 声明添加到表单类:
[DllImport("user32.dll")]
static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
并添加以下常量:
private const int SWP_NOMOVE = 0x0002;
private const int SWP_NOSIZE = 0x0001;
private const int SWP_SHOWWINDOW = 0x0040;
private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
我希望这会有所帮助!