C#窗体面积计算器
时间: 2023-07-12 07:22:07 浏览: 56
好的,下面是一个简单的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)
{
if (cmbShape.SelectedIndex == 0) // 计算圆面积
{
double radius;
if (double.TryParse(txtRadius.Text, out radius))
{
double area = Math.PI * radius * radius;
txtResult.Text = area.ToString("f2");
}
else
{
MessageBox.Show("请输入有效的半径!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtRadius.Focus();
}
}
else if (cmbShape.SelectedIndex == 1) // 计算球表面积
{
double radius;
if (double.TryParse(txtRadius.Text, out radius))
{
double area = 4 * Math.PI * radius * radius;
txtResult.Text = area.ToString("f2");
}
else
{
MessageBox.Show("请输入有效的半径!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtRadius.Focus();
}
}
}
}
}
```
这是一个简单的面积计算器,支持计算圆和球的面积。在窗体上放置了一个组合框(用于选择要计算的形状)、两个文本框(用于输入半径和显示结果)和一个计算按钮。当用户点击计算按钮时,程序会根据选择的形状计算相应的面积,并将结果显示在文本框中。如果用户没有输入有效的半径,程序会弹出一个错误提示框,并将焦点设置到半径文本框中。
希望这个示例代码能够帮助到您!
相关推荐
![](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)
![](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)
![](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)