Si las ventanas se abren, entonces alguien lo necesita

Una vez que necesitaba abrir una ventana desde una aplicación de consola. Quería hacer esto usando wpf, pero había poca información dispersa en la red, así que decidí organizar y enviar este pequeño tutorial de alguna manera.

Cree una aplicación de consola normal en el marco .net.



Ahora necesita agregar las dependencias: WindowsBase, PresentationCore, PresentationFramework.



Agregue la clase de nuestra ventana, heredandola de las ventanas estándar de Windows.

public class MyWindow : Window{} 

Agregue el atributo [STAThread] al método principal

Porque
STAThreadAttribute es esencialmente un requisito previo para la mensajería con un servidor de mensajes de Windows con componentes COM
Y con más detalle.


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

Ahora crea nuestra ventana:

  [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; } 

Si ahora llamamos al método Show () en la ventana, se colapsa de inmediato, y dado que nos gustaría mirarlo todo el tiempo, necesitamos insertar esta ventana en un contenedor que admita todo el ciclo de vida.

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

Mostramos una ventana, y se siente bastante bien, pero cerrarlo desde el código es muy fácil: el método Run () es un bucle infinito, y la aplicación solo se puede detener desde el mismo hilo donde se llama. Salida:

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

Entonces todo el método se ve
entonces
 [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(); } 

y aquí está la fuente


Una solución agradable no es hacer que nuestra ventana quede sin código, sino cambiar al xaml más familiar.

Para hacer esto, agregue la dependencia System.Xml.
Y hacer un documento 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> 


Ahora cargue los datos del archivo.
 XmlTextReader r = new XmlTextReader("MyWin.xaml"); var win = XamlReader.Load(r) as Window; 


Y en este caso, el aspecto principal final
entonces
 [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(); } 



PS
Gracias al # chat en tg y al usuario Yuri .

Source: https://habr.com/ru/post/437642/


All Articles