How to programmatically create a WPF window in a WinForm application

前端 未结 2 1660
萌比男神i
萌比男神i 2020-12-10 13:34

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

2条回答
  •  囚心锁ツ
    2020-12-10 14:00

    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();
    

提交回复
热议问题