在WPF窗口中打开记事本

时间:2017-10-14 14:08:05

标签: c# wpf

您可以使用以下代码在WinForm中打开记事本:

public partial class Form1 : Form
    {
        [DllImport("user32.dll")]
        static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
        public Form1()
        {
            InitializeComponent();

            Process p = Process.Start("notepad.exe");
            p.WaitForInputIdle(); // Allow the process to open it's window
            SetParent(p.MainWindowHandle, this.Handle);
        }
    }

在WPF this.handle中无法识别。什么是这个的WPF版本。手柄?

如果没有WPF屏幕中的关闭按钮,如何全屏打开记事本?

1 个答案:

答案 0 :(得分:3)

当寡妇有WindowInteropHelperLoaded时,您可以使用SourceInitialized获取WPF窗口的句柄。在构造函数方法中,尚未创建句柄,它返回零的句柄。试一试:

public MainWindow()
{
    InitializeComponent();

    Loaded += (s, e) =>
    {
        Process p = Process.Start("notepad.exe");
        p.WaitForInputIdle(); // Allow the process to open it's window
        SetParent(p.MainWindowHandle, new System.Windows.Interop.WindowInteropHelper(this).Handle);
    };
}

可替换地,

protected override void OnSourceInitialized(EventArgs e)
{
    base.OnSourceInitialized(e);

    Process p = Process.Start("notepad.exe");
    p.WaitForInputIdle(); // Allow the process to open it's window
    SetParent(p.MainWindowHandle, new System.Windows.Interop.WindowInteropHelper(this).Handle);
}