2011-02-02 101 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(); 
相关问题