如果窗户打开,那么有人需要

一旦我需要从控制台应用程序中打开一个窗口。 我想使用wpf进行此操作,但是网络上散布的信息很少,所以我决定以某种方式组织和提交此小教程。

在.net框架上创建一个常规的控制台应用程序。



现在,您需要添加依赖项:WindowsBase,PresentationCore,PresentationFramework。



添加窗口的类,从Windows的标准窗口继承它。

public class MyWindow : Window{} 

将[STAThread]属性添加到main方法

为何
STAThreadAttribute本质上是与具有COM组件的Windows消息服务器进行消息传递的前提条件
并且更详细。


 [STAThread] public static void Main(string[] args){} 

现在创建我们的窗口:

  [STAThread] public static void Main(string[] args) { var win = new MyWindow { Width = 350, Height = 350}; var grid = new Grid(); var text = new TextBox {Text = "my text"}; grid.Children.Add(text); win.Content = grid; } 

如果现在在窗口上调用Show()方法,它将立即折叠,并且由于我们一直希望查看它,因此我们需要将该窗口推入支持整个生命周期的容器中。

 app.MainWindow = win; app.MainWindow.Show(); app.Run(); 

我们已经显示了一个窗口,感觉不错,但是从代码中关闭它并不是那么容易:Run()方法是一个无限循环,并且Application只能从调用它的同一线程停止。 输出:

 Task.Run(async () => { await Task.Delay(1000); app.Dispatcher.Invoke((Action) delegate { app.Shutdown(); }); }); ; 

然后整个方法看起来
这样
 [STAThread] public static void Main(string[] args) { var app = new Application(); var win = new MyWindow { Width = 350, Height = 350}; var grid = new Grid(); var text = new TextBox {Text = "my text"}; grid.Children.Add(text); win.Content = grid; app.MainWindow = win; app.MainWindow.Show(); Task.Run(async () => { await Task.Delay(1000); app.Dispatcher.Invoke((Action) delegate { app.Shutdown(); }); }); app.Run(); } 

这是来源


一个令人愉快的解决方案不是使我们的窗口不再使用代码,而是切换到更加熟悉的xaml。

为此,添加依赖项System.Xml。
并制作一个XAML文件。
 <Window 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:ConsoleApplication1" mc:Ignorable="d" Title="MyWindow" Height="450" Width="800"> <Grid> <Label Content="Label" /> </Grid> </Window> 


现在从文件加载数据。
 XmlTextReader r = new XmlTextReader("MyWin.xaml"); var win = XamlReader.Load(r) as Window; 


在这种情况下,最终的Main外观
这样
 [STAThread] public static void Main(string[] args) { var app = new Application(); XmlTextReader r = new XmlTextReader("MyWin.xaml"); var win = XamlReader.Load(r) as Window; app.MainWindow = win; app.MainWindow.Show(); Task.Run(async () => { await Task.Delay(1000); app.Dispatcher.Invoke((Action) delegate { app.Shutdown(); }); }); app.Run(); } 



聚苯乙烯
感谢tg中的#chat和用户Yuri

Source: https://habr.com/ru/post/zh-CN437642/


All Articles