把.net core WebAPI托管给窗体Winform或WPF程序

作为程序员,我们的生产皆来源于需求,本次的需求是把.Net core WebAPI托管进窗体程序,缘由是.net core的控制台窗口很容易被人误关,常见的办法是把程序做成windows服务,开机自启,不过windows服务是完全隐藏的,如果用户想在任务栏中看到进程,想在退出时输入密码确认,我暂时能想到的就是用窗体程序接管WebAPI程序,需求不是非常好,但也合情合理。

废话不多说,进入正题。

首先,我这里用WPF来实现(Winform也是基本一样的),计划是在窗体程序中,不仅接管WebAPI程序,同时把控制台的内容输出到WPF的富文本中,关闭窗体程序后,最小化到系统托盘,右键程序图标,可恢复窗口、可退出进程。

vs中创建WPF程序后,修改主窗体及后置代码:

<Window x:Class="NETCore.ApiHosted.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:NETCore.ApiHosted"
        mc:Ignorable="d"
        Title="NETCore.ApiHosted" Height="450" Width="800">
    <Grid>
        <ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto">
            <RichTextBox Name="rtbOutput" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
        </ScrollViewer>
    </Grid>
</Window>

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private NotifyIcon notifyIcon;
        private ContextMenuStrip contextMenuStrip;
        private Process webApiProcess;


        public MainWindow()
        {
            this.InitializeComponent();


            // 将WebAPI控制台输出重定向到WPF窗口
            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                Arguments = "/c dotnet HostedConsole.dll",
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true
     
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Boogaloo-Jer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值