I wanted to make a program that prints "Ah" if the start button is activated, I tried this:
using System;
using System.Collections.Generic;
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 Spam_Spammer
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
while (true)
{
if (start.IsEnabled == false)
{
System.Diagnostics.Debug.WriteLine("Ah");
}
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
start.IsEnabled = false;
stop.IsEnabled = true;
check.IsEnabled = false;
spam_text.IsEnabled = false;
endpoint.IsEnabled = false;
}
private void Stop_Click(object sender, RoutedEventArgs e)
{
start.IsEnabled = true;
stop.IsEnabled = false;
check.IsEnabled = true;
spam_text.IsEnabled = true;
endpoint.IsEnabled = true;
}
}
}
but when I launch the program, it looks like the program is launched, except the actual UI is not here? Any fixes?
The window isn't opening properly because it never leaves its constructor. You can run the code as a Task
from the button click so it doesn't block the UI thread.
public partial class MainWindow : Window
{
static volatile bool running = false;
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (running)
return;
running = true;
Task.Run(() =>
{
while (running)
{
Debug.WriteLine("Running");
}
});
}
private void stop_Click(object sender, RoutedEventArgs e)
{
running = false;
}
}
Note that Task.Run()
returns almost immediately (hence letting the calling method finish) but the Task itself will continue running. This way you don't have to completely disable UI elements either.