且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

.NET Windows窗体透明的控制

更新时间:2023-12-06 11:07:16

你能做到这一点。NET / C#?

Can you do this in .NET/C#?

是的,你当然可以,但需要的一点点努力。我建议以下办法。创建无边框或标题栏区域中的***表,然后给确保它不会吸引客户区背景的TransparencyKey和背景色设置为相同的值。所以,你现在有没有画一个窗口...

Yes you certainly can but it takes a little bit of effort. I would recommend the following approach. Create a top level Form that has no border or titlebar area and then give make sure it draws no client area background by setting the TransparencyKey and BackColor to the same value. So you now have a window that draws nothing...

public class DarkenArea : Form
{
    public DarkenArea()
    {
        FormBorderStyle = FormBorderStyle.None;
        SizeGripStyle = SizeGripStyle.Hide;
        StartPosition = FormStartPosition.Manual;
        MaximizeBox = false;
        MinimizeBox = false;
        ShowInTaskbar = false;
        BackColor = Color.Magenta;
        TransparencyKey = Color.Magenta;
        Opacity = 0.5f;
    }
}

在窗体的客户区创建和地位这一DarkenArea窗口。然后,你需要能够显示窗口,而不考虑它的重点,所以你需要平台调用下列方式没有它变得活跃,显示...

Create and position this DarkenArea window over the client area of your form. Then you need to be able to show the window without it taking the focus and so you will need to platform invoke in the following way to show without it becoming active...

public void ShowWithoutActivate()
{
    // Show the window without activating it (i.e. do not take focus)
    PlatformInvoke.ShowWindow(this.Handle, (short)SW_SHOWNOACTIVATE);
}

您需要使其实际绘制的东西,但排除要继续强调控制的区域图。因此重写OnPaint处理和​​黑色/蓝色或任何你想要的,但不包括该地区吸引你要保持光亮......

You need to make it actually draw something but exclude drawing in the area of the control you want to remain highlighted. So override the OnPaint handler and draw in black/blue or whatever you want but excluding the area you want to remain bright...

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    // Do your painting here be exclude the area you want to be brighter
}

最后,你需要重写WndProc以prevent鼠标与窗口交互如果用户尝试一些疯狂喜欢点击黑暗区域。事情是这样的......

Last you need to override the WndProc to prevent the mouse interacting with the window if the user tries something crazy like clicking on the darkened area. Something like this...

protected override void WndProc(ref Message m)
{
    if (m.Msg == (int)WM_NCHITTEST)
        m.Result = (IntPtr)HTTRANSPARENT;
    else
        base.WndProc(ref m);
}

这应该足以让预期的效果。当您准备扭转你处置DarkenArea实例的影响而矣。

That should be enough to get the desired effect. When you are ready to reverse the effect you dispose of the DarkenArea instance and carry on.