Simple WPF: WPF 透明窗體和滑鼠事件穿透

来源:https://www.cnblogs.com/mrchip/p/18278976
-Advertisement-
Play Games

一個自定義WPF窗體的解決方案,借鑒了呂毅老師的WPF製作高性能的透明背景的異形視窗一文,併在此基礎上增加了滑鼠穿透的功能。可以使得透明窗體的滑鼠事件穿透到下層,在下層窗體中響應。 ...


一個自定義WPF窗體的解決方案,借鑒了呂毅老師的WPF製作高性能的透明背景的異形視窗一文,併在此基礎上增加了滑鼠穿透的功能。可以使得透明窗體的滑鼠事件穿透到下層,在下層窗體中響應。

這個方法不一定是製作WPF透明窗體最合適的方法,請各路大大不要噴。
完整代碼地址:Github

一、 去除標題欄

去除標題欄的方式非常簡單,就是設置WindowStyleNone

<Window x:Class="NonFrameWindow.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:NonFrameWindow"
        mc:Ignorable="d"
        WindowStyle ="None" ResizeMode="CanMinimize"
        Title="MainWindow" Height="450" Width="800">

image

二、 設置窗體模板顯示透明背景和內容

使用WindowChrome類自定義窗體樣式,設置 GlassFrameThickness 為-1表示遮擋住整個原生視窗。設置Window模板增加透明的邊框背景,嵌套一個圓角邊框並配置陰影屬性,在邊框中展示其他內容控制項

    <WindowChrome.WindowChrome>
        <WindowChrome GlassFrameThickness="-1"/>
    </WindowChrome.WindowChrome>
    <Window.Template>
        <ControlTemplate TargetType="Window">
            <Border Padding="64" Background="Transparent">
                <Border CornerRadius="16" Background="#10FF1010">
                    <Border.Effect>
                        <DropShadowEffect BlurRadius="64" />
                    </Border.Effect>
                    <ContentPresenter ClipToBounds="True" />
                </Border>
            </Border>
        </ControlTemplate>
    </Window.Template>

image

三、設置視窗屬性使得滑鼠事件穿透到下層窗體

引入user32.dll的函數,進行設置

private const int WS_EX_TRANSPARENT = 0x20;

private const int GWL_EXSTYLE = -20;

[DllImport("user32", EntryPoint = "SetWindowLong")]
private static extern uint SetWindowLong(IntPtr hwnd, int nIndex, uint dwNewLong);

[DllImport("user32", EntryPoint = "GetWindowLong")]
private static extern uint GetWindowLong(IntPtr hwnd, int nIndex);

在Window初始化時,通過調用Windows APISetWindowLong設置視窗屬性可以被穿透

<Window x:Class="MouseTransparentWindow.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MouseTransparentWindow"
        mc:Ignorable="d"
        WindowStyle="None" ResizeMode="CanMinimize" AllowsTransparency="True"
        Title="MainWindow" Height="450" Width="800" SourceInitialized="Window_SourceInitialized">

在Xaml代碼中還修改Window的xaml標簽的屬性,增加允許穿透和資源初始化事件處理函數

演示效果

image
滑鼠無法穿透

image

SetWindowLong接受的GWL_EXSTYLE屬性

Constant value Description
WS_EX_ACCEPTFILES
0x00000010L
The window accepts drag-drop files.
WS_EX_APPWINDOW
0x00040000L
Forces a top-level window onto the taskbar when the window is visible.
WS_EX_CLIENTEDGE
0x00000200L
The window has a border with a sunken edge.
WS_EX_COMPOSITED
0x02000000L
Paints all descendants of a window in bottom-to-top painting order using double-buffering. Bottom-to-top painting order allows a descendent window to have translucency (alpha) and transparency (color-key) effects, but only if the descendent window also has the WS_EX_TRANSPARENT bit set. Double-buffering allows the window and its descendents to be painted without flicker. This cannot be used if the window has a class style of either CS_OWNDC or CS_CLASSDC.
Windows 2000: This style is not supported.
WS_EX_CONTEXTHELP
0x00000400L
The title bar of the window includes a question mark. When the user clicks the question mark, the cursor changes to a question mark with a pointer. If the user then clicks a child window, the child receives a WM_HELP message. The child window should pass the message to the parent window procedure, which should call the WinHelp function using the HELP_WM_HELP command. The Help application displays a pop-up window that typically contains help for the child window.
WS_EX_CONTEXTHELP cannot be used with the WS_MAXIMIZEBOX or WS_MINIMIZEBOX styles.
WS_EX_CONTROLPARENT
0x00010000L
The window itself contains child windows that should take part in dialog box navigation. If this style is specified, the dialog manager recurses into children of this window when performing navigation operations such as handling the TAB key, an arrow key, or a keyboard mnemonic.
WS_EX_DLGMODALFRAME
0x00000001L
The window has a double border; the window can, optionally, be created with a title bar by specifying the WS_CAPTION style in the dwStyle parameter.
WS_EX_LAYERED
0x00080000
The window is a layered window. This style cannot be used if the window has a class style of either CS_OWNDC or CS_CLASSDC.
Windows 8: The WS_EX_LAYERED style is supported for top-level windows and child windows. Previous Windows versions support WS_EX_LAYERED only for top-level windows.
WS_EX_LAYOUTRTL
0x00400000L
If the shell language is Hebrew, Arabic, or another language that supports reading order alignment, the horizontal origin of the window is on the right edge. Increasing horizontal values advance to the left.
WS_EX_LEFT
0x00000000L
The window has generic left-aligned properties. This is the default.
WS_EX_LEFTSCROLLBAR
0x00004000L
If the shell language is Hebrew, Arabic, or another language that supports reading order alignment, the vertical scroll bar (if present) is to the left of the client area. For other languages, the style is ignored.
WS_EX_LTRREADING
0x00000000L
The window text is displayed using left-to-right reading-order properties. This is the default.
WS_EX_MDICHILD
0x00000040L
The window is a MDI child window.
WS_EX_NOACTIVATE
0x08000000L
A top-level window created with this style does not become the foreground window when the user clicks it. The system does not bring this window to the foreground when the user minimizes or closes the foreground window.
The window should not be activated through programmatic access or via keyboard navigation by accessible technology, such as Narrator.
To activate the window, use the SetActiveWindow or SetForegroundWindow function.
The window does not appear on the taskbar by default. To force the window to appear on the taskbar, use the WS_EX_APPWINDOW style.
WS_EX_NOINHERITLAYOUT
0x00100000L
The window does not pass its window layout to its child windows.
WS_EX_NOPARENTNOTIFY
0x00000004L
The child window created with this style does not send the WM_PARENTNOTIFY message to its parent window when it is created or destroyed.
WS_EX_NOREDIRECTIONBITMAP
0x00200000L
The window does not render to a redirection surface. This is for windows that do not have visible content or that use mechanisms other than surfaces to provide their visual.
WS_EX_OVERLAPPEDWINDOW
(WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE)
The window is an overlapped window.
WS_EX_PALETTEWINDOW
(WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST)
The window is palette window, which is a modeless dialog box that presents an array of commands.
WS_EX_RIGHT
0x00001000L
The window has generic "right-aligned" properties. This depends on the window class. This style has an effect only if the shell language is Hebrew, Arabic, or another language that supports reading-order alignment; otherwise, the style is ignored.
Using the WS_EX_RIGHT style for static or edit controls has the same effect as using the SS_RIGHT or ES_RIGHT style, respectively. Using this style with button controls has the same effect as using BS_RIGHT and BS_RIGHTBUTTON styles.
WS_EX_RIGHTSCROLLBAR
0x00000000L
The vertical scroll bar (if present) is to the right of the client area. This is the default.
WS_EX_RTLREADING
0x00002000L
If the shell language is Hebrew, Arabic, or another language that supports reading-order alignment, the window text is displayed using right-to-left reading-order properties. For other languages, the style is ignored.
WS_EX_STATICEDGE
0x00020000L
The window has a three-dimensional border style intended to be used for items that do not accept user input.
WS_EX_TOOLWINDOW
0x00000080L
The window is intended to be used as a floating toolbar. A tool window has a title bar that is shorter than a normal title bar, and the window title is drawn using a smaller font. A tool window does not appear in the taskbar or in the dialog that appears when the user presses ALT+TAB. If a tool window has a system menu, its icon is not displayed on the title bar. However, you can display the system menu by right-clicking or by typing ALT+SPACE.
WS_EX_TOPMOST
0x00000008L
The window should be placed above all non-topmost windows and should stay above them, even when the window is deactivated. To add or remove this style, use the SetWindowPos function.
WS_EX_TRANSPARENT
0x00000020L
The window should not be painted until siblings beneath the window (that were created by the same thread) have been painted. The window appears transparent because the bits of underlying sibling windows have already been painted.
To achieve transparency without these restrictions, use the SetWindowRgn function.
WS_EX_WINDOWEDGE
0x00000100L
The window has a border with a raised edge.
WS_EX_TRANSPARENT
0x00000020L
The window should not be painted until siblings beneath the window (that were created by the same thread) have been painted. The window appears transparent because the bits of underlying sibling windows have already been painted.
To achieve transparency without these restrictions, use the SetWindowRgn function.
----- -----

參考鏈接

https://blog.walterlv.com/post/wpf-transparent-window-without-allows-transparency.html

https://www.cnblogs.com/dino623/p/problems_of_WindowChrome.html#idx_7

https://www.yuantk.com/weblog/a9ca4f90-56fc-4c8f-bc93-15d63fda4f57.html

https://blog.51cto.com/u_5496753/5263789

https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowlonga

https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowlonga

https://learn.microsoft.com/en-us/windows/win32/winmsg/extended-window-styles

https://learn.microsoft.com/en-us/dotnet/api/system.windows.shell.windowchrome?view=windowsdesktop-7.0


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 實現了一個支持長短按得按鈕組件,單擊可以觸發Click事件,長按可以觸發LongPressed事件,長按鬆開時觸發LongClick事件。還可以和自定義外觀相結合,實現自定義的按鈕外形。 ...
  • WPF的按鈕提供了Template模板,可以通過修改Template模板中的內容對按鈕的樣式進行自定義。結合資源字典,可以將自定義資源在xaml視窗、自定義控制項或者整個App當中調用 ...
  • 在 Visual Studio 中,至少可以創建三種不同類型的類庫: 類庫(.NET Framework) 類庫(.NET 標準) 類庫 (.NET Core) 雖然第一種是我們多年來一直在使用的,但一直感到困惑的一個主要問題是何時使用 .NET Standard 和 .NET Core 類庫類型。 ...
  • 之前也分享過 Swashbuckle.AspNetCore 的使用,不過版本比較老了,本次演示用的示例版本為 .net core 8.0,從安裝使用開始,到根據命名空間分組顯示,十分的有用 ...
  • 1.簡單使用實例 1.1 添加log4net.dll的引用。 在NuGet程式包中搜索log4net並添加,此次我所用版本為2.0.17。如下圖: 1.2 添加配置文件 右鍵項目,添加新建項,搜索選擇應用程式配置文件,命名為log4net.config,步驟如下圖: 1.2.1 log4net.co ...
  • 最近在微軟商店,官方上架了新款Win11風格的WPF版UI框架【WPF Gallery Preview 1.0.0.0】,這款應用引入了前沿的Fluent Design UI設計,為用戶帶來全新的視覺體驗。 ...
  • 當你使用Edge等瀏覽器或系統軟體播放媒體時,Windows控制中心就會出現相應的媒體信息以及控制播放的功能,如圖。 SMTC (SystemMediaTransportControls) 是一個Windows App SDK (舊為UWP) 中提供的一個API,用於與系統媒體交互。接入SMTC的好 ...
  • 在C#中使用RabbitMQ做個簡單的發送郵件小項目 前言 好久沒有做項目了,這次做一個發送郵件的小項目。發郵件是一個比較耗時的操作,之前在我的個人博客裡面回覆評論和友鏈申請是會通過發送郵件來通知對方的,不過當時只是簡單的進行了非同步操作。 那麼這次來使用RabbitMQ去統一發送郵件,我的想法是通過 ...
一周排行
    -Advertisement-
    Play Games
  • 通過WPF的按鈕、文本輸入框實現了一個簡單的SpinBox數字輸入用戶組件並可以通過數據綁定數值和步長。本文中介紹了通過Xaml代碼實現自定義組件的佈局,依賴屬性的定義和使用等知識點。 ...
  • 以前,我看到一個朋友在對一個系統做初始化的時候,通過一組魔幻般的按鍵,調出來一個隱藏的系統設置界面,這個界面在常規的菜單或者工具欄是看不到的,因為它是一個後臺設置的關鍵界面,不公開,同時避免常規用戶的誤操作,它是作為一個超級管理員的入口功能,這個是很不錯的思路。其實Winform做這樣的處理也是很容... ...
  • 一:背景 1. 講故事 前些天有位朋友找到我,說他的程式每次關閉時就會自動崩潰,一直找不到原因讓我幫忙看一下怎麼回事,這位朋友應該是第二次找我了,分析了下 dump 還是挺經典的,拿出來給大家分享一下吧。 二:WinDbg 分析 1. 為什麼會崩潰 找崩潰原因比較簡單,用 !analyze -v 命 ...
  • 在一些報表模塊中,需要我們根據用戶操作的名稱,來動態根據人員姓名,更新報表的簽名圖片,也就是電子手寫簽名效果,本篇隨筆介紹一下使用FastReport報表動態更新人員簽名圖片。 ...
  • 最新內容優先發佈於個人博客:小虎技術分享站,隨後逐步搬運到博客園。 創作不易,如果覺得有用請在Github上為博主點亮一顆小星星吧! 博主開始學習編程於11年前,年少時還只會使用cin 和cout ,給單片機點點燈。那時候,類似async/await 和future/promise 模型的認知還不是 ...
  • 之前在阿裡雲ECS 99元/年的活動實例上搭建了一個測試用的MINIO服務,以前都是直接當基礎設施來使用的,這次準備自己學一下S3相容API相關的對象存儲開發,因此有了這個小工具。目前僅包含上傳功能,後續計劃開發一個類似圖床的對象存儲應用。 ...
  • 目錄簡介快速入門安裝 NuGet 包實體類User資料庫類DbFactory增刪改查InsertSelectUpdateDelete總結 簡介 NPoco 是 PetaPoco 的一個分支,具有一些額外的功能,截至現在 github 星數 839。NPoco 中文資料沒多少,我是被博客園群友推薦的, ...
  • 前言 前面使用 Admin.Core 的代碼生成器生成了通用代碼生成器的基礎模塊 分組,模板,項目,項目模型,項目欄位的基礎功能,本篇繼續完善,實現最核心的模板生成功能,並提供生成預覽及代碼文件壓縮下載 準備 首先清楚幾個模塊的關係,如何使用,簡單畫一個流程圖 前面完成了基礎的模板組,模板管理,項目 ...
  • 假設需要實現一個圖標和文本結合的按鈕 ,普通做法是 直接重寫該按鈕的模板; 如果想作為通用的呢? 兩種做法: 附加屬性 自定義控制項 推薦使用附加屬性的形式 第一種:附加屬性 創建Button的附加屬性 ButtonExtensions 1 public static class ButtonExte ...
  • 在C#中,委托是一種引用類型的數據類型,允許我們封裝方法的引用。通過使用委托,我們可以將方法作為參數傳遞給其他方法,或者將多個方法組合在一起,從而實現更靈活的編程模式。委托類似於函數指針,但提供了類型安全和垃圾回收等現代語言特性。 基本概念 定義委托 定義委托需要指定它所代表的方法的原型,包括返回類 ...