我正在使用C#创建一个与Arduino串行通信的应用程序。我有按钮,通过连续发送某些字母告诉Arduino该怎么做。 Arduino将控制RGB LED灯条。但我希望用户能够添加按钮并在用户按下按钮时显示将发送的RGB值。我已经想出了如何添加按钮和所有但我想知道如何为已添加的每个按钮创建单独的事件处理程序。
int h = 5;
int l = 5;
private void addButton_Click(object sender, EventArgs e)
{
Point newLoc = new Point(h, l);
List<Button> buttons = new List<Button>();
Button newButton = new Button();
newButton.Text = buttonNameTextBox.Text;
newButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(253)))), ((int)(((byte)(199)))), ((int)(((byte)(13)))));
newButton.Size = new Size(150, 50);
newButton.Font = new System.Drawing.Font("Calibri", 15F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
newButton.Location = newLoc;
newLoc.Offset(0, newButton.Height + 5);
newButton.
buttons.Add(newButton);
newButton.Name = componentNameTextBox.Text;
this.Controls.Add(newButton);
l += 65;
newButton.Click += new EventHandler(newButton_Click);
}
所以我必须创建按钮并放置按钮。我的最终目标是能够让用户输入他们希望LED的RGB值,以便当按下按钮时它将发送它们。
答案 0 :(得分:1)
对所有这些事件使用相同的事件处理程序(即sender
),并使用int h = 5;
int l = 5;
private void addButton_Click(object sender, EventArgs e)
{
Point newLoc = new Point(h, l);
List<Button> buttons = new List<Button>();
Button newButton = new Button();
newButton.Text = buttonNameTextBox.Text;
newButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(253)))), ((int)(((byte)(199)))), ((int)(((byte)(13)))));
newButton.Size = new Size(150, 50);
newButton.Font = new System.Drawing.Font("Calibri", 15F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
newButton.Location = newLoc;
newLoc.Offset(0, newButton.Height + 5);
newButton.
buttons.Add(newButton);
newButton.Name = componentNameTextBox.Text;
this.Controls.Add(newButton);
l += 65;
newButton.Click += (s, ea) => {
//Here is an event handler just for this button. You can access
//the surrounding variables (such as l, or newButton.BackColor etc) right here.
};
}
参数来确定单击哪一个,或者使用可以访问所有权限的内联lambda函数周围的变量已经:
private void addButton_Click(object sender, EventArgs e)
{
/* as before... */
int red = Convert.ToInt32(txtRed.Text);
int green = Convert.ToInt32(txtGreen.Text);
int blue = Convert.ToInt32(txtBlue.Text);
newButton.BackColor = System.Drawing.Color.FromArgb(red, green, blue);
newButton.Click += (s, ea) => {
//made up function call to show how you can use the rgb values inline here
ArduinoController.SendRGB(red, green, blue);
}
}
您说您希望允许用户传入值 - 假设您可能有3个文本框,这意味着此函数可能如下所示:
private static void addToZip(final String filename, final String zipfile)
throws IOException
{
final Path path = Paths.get(filename);
final URI uri = URI.create("jar:" + Paths.get(zipfile).toUri());
final Map<String, ?> env = Collections.emptyMap();
Path pathInZip;
try (
final FileSystem fs = FileSystems.newFileSystems(uri, env);
) {
pathInZip = fs.getPath(path.getFileName().toString());
Files.copy(path, pathInZip);
}
}