开发者

How to programmatically create a WPF window in a WinForm application

I have an existing WinForm app which is too much to port to WPF right now. However, I need a window with some tricky transparency behavior that I cannot achieve in a WinForm (yes, tried Layerd Windows but it's a no-go).

WPF allows the transparency behavior I need beautifully and simply.

I googled of course, but can only find hints how to create a WPF control within a WinForm but that is NOT what I need. I need a separate WPF window that is completely independant of my other Forms.

The WPF window will be a rather simple full-screen and borderless ov开发者_StackOverflowerlay window where I will do some simple drawings, each with different transparencies.

How can I create a WPF window within a WinForm application?


Add the necessary WPF references to your project, create a WPF Window-instance, call EnableModelessKeyboardInterop and show the window.

The call to EnableModelessKeyboardInterop makes sure, that your WPF window will get keyboard inputs from your Windows Forms app.

Take care, if you open a new Window from within your WPF window, the keyboard input will not be routed to this new window. You have to call also for these newly created windows EnableModelessKeyboardInterop.

Fore your other requirements, use Window.Topmost and Window.AllowsTransparency. Don't forget to set the WindowStyle to None, otherwise, transparency is not supported.

Update
The following references should be added to use WPF in your windows forms application:

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


Here's the (tested) solution. This code can be used in both a WinForm or a WPF app. No XAML needed at all.

#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;
    }
}

The window background is fully transparent. You can draw on the canvas and each element can have it's own transparency (which you can determine by setting the alpha channel of the Brush used to draw it). Simply invoke the window with something like

WPFWindow w = new WPFWindow();
w.Show();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜