繁体   English   中英

如何以编程方式在WinForm应用程序中创建WPF窗口

[英]How to programmatically create a WPF window in a WinForm application

我有一个现有的WinForm应用程序,现在太多了,无法移植到WPF。 但是,我需要一个窗口,其中包含一些我在WinForm中无法实现的棘手的透明行为(是的,尝试了Layerd Windows,但它是不行的)。

WPF允许我所需要的透明度行为非常简单。

我当然用Google搜索,但只能找到如何在WinForm中创建WPF控件的提示,但这不是我需要的。 我需要一个单独的WPF窗口,它完全独立于我的其他窗体。

WPF窗口将是一个相当简单的全屏和无边框覆盖窗口,我将在其中执行一些简单的绘图,每个绘图都有不同的透明度。

如何在WinForm应用程序中创建WPF窗口?

向项目添加必要的WPF引用,创建WPF Window -instance,调用EnableModelessKeyboardInterop并显示窗口。

EnableModelessKeyboardInterop的调用确保您的WPF窗口将从Windows窗体应用程序获得键盘输入。

请注意,如果从WPF窗口中打开一个新窗口,键盘输入将不会路由到此新窗口。 您还必须为这些新创建的窗口EnableModelessKeyboardInterop

根据您的其他要求,使用Window.TopmostWindow.AllowsTransparency 不要忘记将WindowStyle设置为None ,否则不支持透明度。

更新
应添加以下引用以在Windows窗体应用程序中使用WPF:

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

这是(测试过的)解决方案。 此代码可以在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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM