This tutorial aims to provide a thorough understanding of creating basic GUI applications using Windows Forms and WPF (Windows Presentation Foundation). By the end of this tutorial, you will have a basic understanding of GUI application development and how to create user-friendly interfaces.
Windows Forms is a GUI library in the .NET framework. It is event-driven, meaning that the program responds to various inputs or events.
Windows Presentation Foundation (WPF) is a UI framework for building Windows desktop applications. WPF offers an extensive suite of controls and flexibility in UI design.
Form1.cs
that represents the main window of your application.You can add controls like buttons, text boxes, labels, etc. to your form using the toolbox in Visual Studio.
Tip: Always remember to name your controls appropriately to maintain clean and understandable code.
// Add a button control to your form
Button button1 = new Button();
button1.Text = "Click me";
button1.Location = new Point(10, 10);
this.Controls.Add(button1);
// Add an event handler for button click event
button1.Click += new EventHandler(button1_Click);
// Define the event handler
void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Button clicked!");
}
In this code, we first create a new button control, set its properties, and add it to the form. We then attach a click event handler to the button. When the button is clicked, a message box will pop up displaying "Button clicked!".
In this tutorial, we have covered the basics of creating a GUI application using Windows Forms and WPF, adding controls to the form, implementing functionality, and testing the application.
Solution:
// Create text boxes and button
TextBox textBox1 = new TextBox();
TextBox textBox2 = new TextBox();
Button button1 = new Button();
// Set properties
// ...
// Add controls to the form
// ...
// Add an event handler for button click event
button1.Click += new EventHandler(button1_Click);
void button1_Click(object sender, EventArgs e)
{
int num1 = Int32.Parse(textBox1.Text);
int num2 = Int32.Parse(textBox2.Text);
int sum = num1 + num2;
MessageBox.Show("The sum is " + sum);
}
Solution:
<!-- XAML code -->
<Grid>
<TextBox Name="textBox1" Margin="10"/>
<Button Content="Submit" Click="Button_Click" Margin="10,60,10,10"/>
<Label Name="label1" Margin="10,30,10,10"/>
</Grid>
// C# code
private void Button_Click(object sender, RoutedEventArgs e)
{
label1.Content = textBox1.Text;
}
Tip: Practice by creating applications with more complex functionality and interfaces.