如何在XAML c#窗口中打开程序

本文关键字:窗口 打开程序 XAML | 更新日期: 2023-09-27 18:02:36

我使用的是Visual Studio 2015 RC (WPF应用程序c#),我希望我的程序打开我的任何应用程序(点击一个按钮)进入我的应用程序窗口,下面的代码是未完成的。

问题只发生在我点击按钮时,记事本在它自己的窗口随机打开,而不是在我的应用程序的画布。

Main.Window.xaml:

<Window x:Class="stackoverflowquestion1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:stackoverflowquestion1"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="0*"/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Menu x:Name="menu" HorizontalAlignment="Left" Height="22" Margin="2,10,0,0" VerticalAlignment="Top" Width="497" Grid.Column="1">
        <Button x:Name="button" Click="button_Click" Width="187">Click here to open Notepad Below</Button>
    </Menu>
    <Canvas Grid.ColumnSpan="2" HorizontalAlignment="Left" Height="257" Margin="10,52,0,0" VerticalAlignment="Top" Width="489" Background="Black"/>
</Grid></Window>

MainWindow.xaml.cs:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace stackoverflowquestion1
{
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void button_Click(object sender, RoutedEventArgs e)
    {
        Process.Start("notepad.exe");
    }
  }
}

如何在XAML c#窗口中打开程序

找到了答案,代码如下:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        Process p = Process.Start("notepad.exe");
        p.WaitForInputIdle(); // Allow the process to open it's window
        SetParent(p.MainWindowHandle, this.Handle);
    }
    [DllImport("user32.dll")]
    static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
}
}

最后一点,我用了一个windows窗体应用程序c#,而不是windows WPF应用程序,我很高兴我找到了答案,哈哈大家

如果您确实在使用WPF,您可以将this.Handle替换为Process.GetCurrentProcess().MainWindowHandle