【问题标题】:Topmost transparent clickable through form with clickable through controls C#最透明的可点击表单,可通过控件点击 C#
【发布时间】:2016-02-05 17:20:40
【问题描述】:

我在透明表单上使用 GDI 绘制了一些矩形。

表单是全屏的,并且总是在顶部。 另外,通过这个方法可以点击: Topmost form, clicking "through" possible?

但是,绘制的矩形无法像我的表单那样点击,而且每次点击它们时我的应用程序都会失去焦点。此外,当我将鼠标悬停在它们上时,我可以看到我的应用光标(窗体下的窗口是一个游戏,因此它有一个自定义光标)。

您能告诉我如何使所有控件都无法聚焦和点击吗?有可能还是我必须使用 DirectX 绘图之类的东西?

我搜索了整个网络和 stackoverflow,使用了各种解决方案,但没有任何效果。

谢谢。

【问题讨论】:

  • 听起来很可疑
  • 通常可见的像素会捕获点击。
  • @Kirill:为什么会这样?

标签: c# winforms transparent


【解决方案1】:

我不确定我是否完全理解您要完成的工作,但是如果您希望制作一个可以接收鼠标点击但不会“窃取”焦点的控件,这是很有可能的:

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);


我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2015-12-31
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    • 2014-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多