2011-02-02 82 views
11

我有一個現有的WinForm應用程序,它太多無法移植到WPF了。 但是,我需要一個窗口,它具有一些我在WinForm中無法實現的棘手的透明行爲(是的,嘗試過Layerd Windows,但它是不可行的)。如何以編程方式在WinForm應用程序中創建WPF窗口

WPF允許我需要美觀而簡單的透明行爲。

我當然搜索了一下,但只能找到提示如何在WinForm中創建一個WPF控件,但這不是我所需要的。我需要一個完全獨立於其他表單的獨立WPF窗口。

WPF窗口將是一個相當簡單的全屏和無邊界覆蓋窗口,我將在這裏執行一些簡單的圖紙,每個圖紙都有不同的透明度。

如何在WinForm應用程序中創建WPF窗口?

+0

,看一下我的回答是:http://stackoverflow.com/questions/8311956/open-wpf-window-in-windowsform-app/32691690#32691690 – 2015-09-21 10:00:55

回答

13

爲您的項目添加必要的WPF引用,創建一個WPF Window -instance,請撥打EnableModelessKeyboardInterop並顯示該窗口。

致電EnableModelessKeyboardInterop確保您的WPF窗口將從Windows窗體應用程序獲取鍵盤輸入。

請注意,如果您從WPF窗口中打開一個新窗口,鍵盤輸入將不會路由到此新窗口。您還必須致電這些新創建的窗口EnableModelessKeyboardInterop

對於您的其他要求,請使用Window.TopmostWindow.AllowsTransparency。不要忘記將WindowStyle設置爲None,否則,不支持透明度。

更新
以下引用應添加在Windows使用WPF窗體應用程序:

  • PresentationCore
  • PresentationFramework
  • System.Xaml
  • WindowsBase
  • WindowsFormsIntegration程序
+0

@Harald:如果我的回答對您有幫助,請將其標記爲已接受的答案。 – HCL 2011-02-04 08:10:53

+0

您的其他信息鏈接不再有效。 – 2016-05-19 15:16:11

6

這是(測試的)解決方案。此代碼可以用於WinForm或WPF應用程序。 根本不需要XAML。

#region WPF 
// include following references: 
// PresentationCore 
// PresentationFramework 
// WindowsBase 

using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Media; 
using System.Windows.Shapes; 
#endregion 


public class WPFWindow : Window 
{ 

    private Canvas canvas = new Canvas(); 

    public WPFWindow() 
    { 
     this.AllowsTransparency = true; 
     this.WindowStyle = WindowStyle.None; 
     this.Background = Brushes.Black; 
     this.Topmost = true; 

     this.Width = 400; 
     this.Height = 300; 
     canvas.Width = this.Width; 
     canvas.Height = this.Height; 
     canvas.Background = Brushes.Black; 
     this.Content = canvas; 
    } 
} 

窗口背景是完全透明的。 您可以在畫布上繪圖,並且每個元素都可以具有自己的透明度(您可以通過設置用於繪製畫筆的畫筆的Alpha通道來確定)。 簡單的東西調用的窗前,彷彿

WPFWindow w = new WPFWindow(); 
w.Show(); 
相關問題