[英]Making a WPF window click-through, but not its controls
首先,我想通过对文本中的点击进行透明来定义我的意思:这意味着点击进入我的窗口而不进行任何处理,直接到下面的任何窗口。 我需要这种行为,因为这个应用程序是一个覆盖游戏。
我搜索了有关使窗口对点击透明的问题。 我想知道是否有办法让窗口本身对点击是透明的,而不是它的控件(如文本框和按钮)。
这是窗口的标记:
<Window x:Class="QuestBrowser.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Quest Browser"
Height="350" Width="525"
AllowsTransparency="True" WindowStyle="None" Topmost="True">
<Window.Background>
<SolidColorBrush Color="White" Opacity="0.1"/>
</Window.Background>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox Name="inputTxtBox"></TextBox>
</Grid>
</Window>
而bellow是使窗口对点击透明的代码(几乎从其他问题复制粘贴,因为我在低级别Windows编程时并不擅长)。
namespace Win32Utils
{
public static class WindowHelper
{
const int WS_EX_TRANSPARENT = 0x00000020;
const int GWL_EXSTYLE = (-20);
public static void SetWindowExTransparent(IntPtr hwnd)
{
var extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_TRANSPARENT);
}
}
}
WindowHelper.SetWindowExTransparent方法是在我的方法Window.OnSourceInitialized的覆盖范围内调用的(正如我在获得透明窗口代码的帖子中所指示的):
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
var hwnd = new WindowInteropHelper(this).Handle;
WindowHelper.SetWindowExTransparent(hwnd);
}
这确实使窗口对点击透明,但我放入的所有控件都是透明的(例如,TextBox)。 有没有办法让Window表面对点击透明,但确保TextBox仍能正常接收鼠标和键盘输入?
出于用户隐私的原因,我想避免使用鼠标和键盘钩子,因为正如我所说的,我对Windows API了解不多。 如果钩子是唯一的方法,我真的很感激“For Dummies”式的解释,说明它们是如何工作的。
你能试试吗?
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1"
Height="300"
Width="300"
AllowsTransparency="True"
WindowStyle="None" >
<Window.Background>
<SolidColorBrush Color="#FFB0B0B0"
Opacity="0.05" />
</Window.Background>
<Grid>
<Button Content="Button"
HorizontalAlignment="Left"
Margin="39,125,0,0"
VerticalAlignment="Top"
Width="75" />
<Label Content="Label"
HorizontalAlignment="Left"
Margin="114,50,0,0"
VerticalAlignment="Top" />
<TextBox HorizontalAlignment="Left"
Height="23"
Margin="101,201,0,0"
TextWrapping="Wrap"
Text="TextBox"
VerticalAlignment="Top"
Width="120" />
</Grid>
</Window>
它的基本功能是创建一个透明的窗口。(点击和Invisble)。 但控件是可见的,而不是点击通过。 或者您可以尝试如何在WPF中创建一个允许鼠标事件通过的半透明窗口
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.