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

Har*_*ald 11 wpf winforms

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

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

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

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

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

HCL*_*HCL 15

向项目添加必要的WPF引用,创建WPF 实例Window,调用EnableModelessKeyboardInterop并显示窗口.

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

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

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

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

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


Har*_*ald 7

这是(测试过的)解决方案.此代码可以在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;
    }
}
Run Code Online (Sandbox Code Playgroud)

窗口背景完全透明.您可以在画布上绘制,每个元素都可以拥有自己的透明度(您可以通过设置用于绘制它的画笔的Alpha通道来确定).只需调用窗口即可

WPFWindow w = new WPFWindow();
w.Show();
Run Code Online (Sandbox Code Playgroud)