在 Win32 编程模型中,您所描述的窗口类型称为“透明”窗口。
请注意,这与opacity不同,它经常被混淆。透明窗口对于鼠标点击等事件是透明的,但它可能仍然是不透明的(即,视觉上不透明)。您可以同时拥有命中测试透明度和视觉透明度,或者只有一种,或者两者都没有。
要使窗口命中测试透明,您需要在创建窗口时设置WS_EX_TRANSPARENT
扩展窗口样式。
要从 VB.NET 执行此操作,请覆盖表单的CreateParams
属性并添加样式标志,如下所示:
Protected Overrides ReadOnly Property CreateParams As CreateParams
Get
Const WS_EX_TRANSPARENT As Integer = &H20
Dim cp As CreateParams = MyBase.CreateParams
cp.ExStyle = cp.ExStyle Or WS_EX_TRANSPARENT
Return cp
End Get
End Property
请注意,当您使窗口透明时,您会得到一个完全透明的窗口,就像您要求的那样。这意味着鼠标点击将完全不可见,包括在非客户区。用户甚至无法单击左上角的关闭框。应用程序必须以编程方式关闭窗口。您需要在设计中考虑到这一点。
打开和关闭样式需要更多代码。您需要 P/Invoke Win32 函数来检索和设置当前窗口样式。例如:
Imports System
Imports System.Windows.Forms
Imports System.Runtime.InteropServices
' ...etc.
Public Class MyForm : Inherits Form
' P/Invoke stuff
Private Const GWL_EXSTYLE As Integer = -20
Private Const WS_EX_TRANSPARENT As Integer = &H20
<DllImport("user32.dll")> _
Private Shared Function GetWindowLongPtr(hWnd As IntPtr, _
nIndex As Integer) As IntPtr
End Function
<DllImport("user32.dll")> _
Private Shared Function SetWindowLongPtr(hWnd As IntPtr, _
nIndex As Integer, _
dwNewLong As IntPtr) As IntPtr
End Function
' Toggling function
Public Sub ToggleClickTransparency()
' Get the form's current extended window styles.
Dim exStyle As IntPtr = GetWindowLongPtr(Me.Handle, GWL_EXSTYLE)
' Determine if the transparency flag is currently set.
If (exStyle Or WS_EX_TRANSPARENT) = WS_EX_TRANSPARENT Then
' Remove the flag.
exStyle = exStyle And (Not WS_EX_TRANSPARENT)
Else
' Add the flag.
exStyle = exStyle Or WS_EX_TRANSPARENT
End If
' Update the window's styles.
SetWindowLongPtr(Me.Handle, GWL_EXSTYLE, exStyle)
End Sub
' Other code
' ...
End Class