我正在Visual Studio 2017中开发计算器。一切工作正常,但键盘输入无法正常工作。 我在按钮的文本属性中使用“&”,它可以工作,但问题在于它正在屏幕上打印,如“& 1 + & 2”。我附上一段代码和图片,以便你们可以看到发生了什么。在键盘上使用“&”在文本属性中输入C#中的计算器
1 - result picture
由于提前, 最好的问候, 拉姆
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Calculator
{
public partial class Form1 : Form
{
Double resultado_value = 0; // result is zero in the beginning
String operationPerformed = "";
bool is_pressed = false;
public Form1()
{
InitializeComponent();
}
private void button_click(object sender, EventArgs e)
{
if ((textBox_Result.Text == "0") || (is_pressed))
textBox_Result.Clear();
is_pressed = false;
Button button = (Button)sender;
if (button.Text == ".") //to avoid repetitive dots
{
if(!textBox_Result.Text.Contains("."))
textBox_Result.Text = textBox_Result.Text + button.Text;
}else
textBox_Result.Text = textBox_Result.Text + button.Text;
}
private void operator_click(object sender, EventArgs e)
{
Button button = (Button)sender;
if (resultado_value != 0) //if result value not equal to zero
{
button15.PerformClick();
operationPerformed = button.Text;
labelCurrentOperation.Text = resultado_value + " " + operationPerformed;
is_pressed = true;
}
else
{
operationPerformed = button.Text;
resultado_value = Double.Parse(textBox_Result.Text);
labelCurrentOperation.Text = resultado_value + " " + operationPerformed;
is_pressed = true;
}
}
//Clear entry
private void button4_Click(object sender, EventArgs e)
{
textBox_Result.Text = "0";
}
//button Clear
private void button5_Click(object sender, EventArgs e)
{
// this.BackColor = System.Drawing.Color.White;//can't find color "control"
textBox_Result.Text = "0";
resultado_value = 0;
}
// equal button
private void button15_Click(object sender, EventArgs e)
{
switch (operationPerformed)
{
case "+":
// this.BackColor = System.Drawing.Color.Red;//form change color to red
textBox_Result.Text = (resultado_value + Double.Parse(textBox_Result.Text)).ToString();
break;
case "-":
// this.BackColor = System.Drawing.Color.Aqua;
textBox_Result.Text = (resultado_value - Double.Parse(textBox_Result.Text)).ToString();
break;
case "X":
// this.BackColor = System.Drawing.Color.AliceBlue;
textBox_Result.Text = (resultado_value * Double.Parse(textBox_Result.Text)).ToString();
break;
case "÷":
// this.BackColor = System.Drawing.Color.BlueViolet;
textBox_Result.Text = (resultado_value/Double.Parse(textBox_Result.Text)).ToString();
break;
default:
break;
}
resultado_value = Double.Parse(textBox_Result.Text);
labelCurrentOperation.Text = "";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void labelCurrentOperation_Click(object sender, EventArgs e)
{
}
}
}
你怎么_expect_它做什么? &并不代表文本框中的任何内容... – john
@john感谢您的评论!当我将“&”放在文本中时,它开始接受来自键盘的输入。但问题在于它正在结果区域中打印。 –
作为一个简单的解决方案,将要实际添加到文本框中的值添加到按钮的“Tag”属性中,然后添加button.Tag.ToString()而不是button.Text。更好的解决方案是分别处理每个按钮并通过其他方法调用。例如点击1调用你创建的方法:插入(“1”)等等 – john