[英]Making a block of code run more than once c# winform
我正在用 c# 编写一种简单的编程语言,以允许用户在文本框中输入命令并将形状绘制到屏幕上,我已经编写了一种方法来执行此操作。 我遇到的问题是该方法一次只绘制一个形状,即使我给它两个命令。
public void RunProgram()
{
try
{
string[] spilt = cp.UserCMD(textInput).Split('(', ')', ','); // spilts on brackets to get numbs inside of brackets
foreach (string cmd in spilt) //spilt string on brackets and comma
{
if (cp.ValidCommand(textInput) == true) //checks if command is valid
{
if (cp.FunctionCMD(textInput) == "reset".ToLower())
{
x = 0;
y = 0;
}
else if (cp.FunctionCMD(textInput) == "moveTo".ToLower())
{
x = Int32.Parse(spilt[1]); //gets x and y from 2nd and 3rd element of spilt array. 1st item is command
y = Int32.Parse(spilt[2]);
}
else if (cmdInput == "clear".ToLower())
{
ClearForm();
}
}
if (cp.FunctionCMD(textInput) == "circle".ToLower())
{
radius = Int32.Parse(spilt[1]); ////gets radius from 2nd element of spilt array. 1st item is command
}
if (cp.FunctionCMD(textInput) == "rectangle".ToLower())
{
width = Int32.Parse(spilt[1]); //gets width and height from 2nd and 3rd element of spilt array. 1st item is command
height = Int32.Parse(spilt[2]);
}
if (cp.FunctionCMD(textInput) == "triangle".ToLower())
{
side1 = Int32.Parse(spilt[1]); //gets sides 2nd and 3rd and 4th element of spilt array. 1st item is command
side2 = Int32.Parse(spilt[2]);
side3 = Int32.Parse(spilt[3]);
}
}
Graphics g;
g = Graphics.FromImage(drawOutput);
Pen pen = new Pen(Color.Black, 5);
if (cp.ValidCommand(textInput) == true) // check if command is valid
{
if (cp.FunctionCMD(textInput) == "circle".ToLower())
{
circle.drawCircle(radius, pen, g, x, y); // draw circle using x and y from spilt array
setImage(g);
}
if (cp.FunctionCMD(textInput) == "rectangle".ToLower())
{
rect.drawRectangle(width, height, pen, g, x, y); // draw rect from width and height from spilt array
setImage(g);
}
if (cp.FunctionCMD(textInput) == "triangle".ToLower())
{
tri.drawTriangle(side1, side2, side3, pen, g); // draw triangle from 3 different sides from spilt array
setImage(g);
}
}
else
{
MessageBox.Show("You have a syntax error, Please check your command"); //if command is not valid then throw
}
}
catch (IndexOutOfRangeException e1)
{
MessageBox.Show("You have a syntax error, Please check your parameters \nError: \n" + e1); // displays messagebox if correct parameters are not given
}
}
上面的代码是被调用的方法。 代码是当我遍历文本框中的行时。
if (cmdInput == "run".ToLower())
{
foreach (var line in InputTxtBox.Lines)
{
System.Diagnostics.Debug.WriteLine(line);
RunProgram();
}
}
if (cmdInput != "run".ToLower())
{
textInput = CMDBox.Text;
RunProgram();
}
如果用户输入: circle(100) rectange(100,100)
预期的结果应该是在屏幕上绘制一个圆形和矩形,但是目前只会绘制一个圆形而不是矩形
我认为问题在于你的 foreach 循环。 首先确保您的文本框已启用多行。
foreach (var line in InputTxtBox.Lines.Count())
应该循环遍历文本框中输入的行数。
foreach (var line in InputTxtBox.Lines.Count())
{
System.Diagnostics.Debug.WriteLine(line);
RunProgram();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.