c#窗体制作简易面积计算器
时间: 2023-07-04 13:27:13 浏览: 79
以下是一个简易的C#窗体面积计算器的代码示例:
```csharp
using System;
using System.Windows.Forms;
namespace AreaCalculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
double width = Convert.ToDouble(txtWidth.Text);
double height = Convert.ToDouble(txtHeight.Text);
double area = width * height;
lblResult.Text = $"The area is {area}";
}
catch (Exception ex)
{
MessageBox.Show($"Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
```
在窗体设计器中,添加两个文本框(用于输入宽度和高度)、一个标签(用于显示计算结果)、一个按钮(用于触发计算)。
然后在窗体的构造函数中初始化控件和事件处理程序:
```csharp
public Form1()
{
InitializeComponent();
btnCalculate.Click += new EventHandler(btnCalculate_Click);
}
```
在事件处理程序中,将文本框中的值转换为双精度浮点数,计算面积并将结果显示在标签上。如果转换或计算过程中出现任何异常,将显示错误消息框。
在这个简单的示例中,我们没有对输入进行任何验证,例如确保输入值是数字或大于零。在实际应用中,您可能需要添加更多的验证以确保输入的正确性。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)