使用TransparencyKey的WS_EX_TOOLWINDOW会导致Win32Exception

时间:2015-06-24 18:04:09

标签: c# winforms transparency

我尝试使用空窗体,但使用工具窗口样式。但是,调用Show()会导致以下异常:

  

Win32Exception:参数不正确。

     

NativeErrorCode:87

     
    

在System.Windows.Forms.Form.UpdateLayered()at     System.Windows.Forms.Control.WmCreate(Message& m)at     System.Windows.Forms.Control.WndProc(Message& m)at     System.Windows.Forms.Form.WmCreate(Message& m)at     System.Windows.Forms.Form.WndProc(Message& m)at     System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,     Int32 msg,IntPtr wparam,IntPtr lparam)

  

错误代码87是ERROR_INVALID_PARAMETER。

private class ToolForm : Form {
    public ToolForm() {
        AllowTransparency = true;
        BackColor = System.Drawing.Color.FromArgb(0, 0, 1);
        TransparencyKey = BackColor;
    }

    private const int WS_EX_TOOLWINDOW = 0x00000080;
    protected override CreateParams CreateParams {
        get {
            var cp = base.CreateParams;
            cp.ExStyle = WS_EX_TOOLWINDOW;
            return cp;
        }
    }
}

修改

这有效:

public class ToolForm : Form {
    public ToolForm() {
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
        this.AllowTransparency = true;
        this.BackColor = Color.FromArgb(0, 0, 1);
        this.TransparencyKey = this.BackColor;
    }
}

1 个答案:

答案 0 :(得分:1)

首先尝试使用OR赋值而不是普通赋值:

cp.ExStyle |= WS_EX_TOOLWINDOW;

如果这不起作用,你可以另外尝试或者选择其中一些相关的风格:

cp.ExStyle |= ( int )(
  WS_EX_LAYERED |
  WS_EX_TRANSPARENT |
  WS_EX_NOACTIVATE |
  WS_EX_TOOLWINDOW );

相关值为:

WS_EX_LAYERED = 0x00080000,
WS_EX_NOACTIVATE = 0x08000000,
WS_EX_TOOLWINDOW = 0x00000080,
WS_EX_TRANSPARENT = 0x00000020

WS_EX_TRANSPARENT标记可能允许您需要的透明度,而不需要TransparencyKey = BackColor;行。