我目前正在做一个项目。但我不太擅长 C#。我需要做的是,打开一个 G 代码文件并从中读取数据,然后通过 USB 将其发送到 CNC 机器。我可以读取数据并发送它。但现在我想读取一行并通过 USB 发送,然后读取下一行。下面我附上了我用来读取 G 代码文件和其他相关数据的代码。
打开 g 代码文件并将所有数据读入文本框:
private void btnopen_Click(object sender, EventArgs e)
{
//OpenFileDialog1.ShowDialog();
OpenFileDialog file = new OpenFileDialog();
file.FileName = "";
file.Title = "Open A Text document.";
file.Filter = "(*.gc)|*.gc|(*.etf)|*.etf|(*.txt)|*.txt|(*.GC)|*.GC|(*.tap)|*.tap";
DialogResult result = file.ShowDialog();
if (result == DialogResult.OK)
{
System.IO.StreamReader OpenFile = new System.IO.StreamReader(file.FileName);
textBox1.Text = OpenFile.ReadToEnd();
OpenFile.Close();
}
从打开的文件中读取 XYZ 坐标:
private void button1_Click(object sender, EventArgs e)
{
Regex Gcode = new Regex("[ngxyzf][+-]?[0-9]*\\.?[0-9]*", RegexOptions.IgnoreCase);
MatchCollection m = Gcode.Matches(this.textBox1.Text);
double X, Y, Z, F;
int g_code = 0;
int x_code = 0, y_code = 0, z_code = 0;
float x = 0, y = 0, z = 0;
foreach (Match n in m)
{
if (n.Value.StartsWith("G"))
{
g_code = Convert.ToInt32(ExtractNumbers(n.Value));
}
if (n.Value.StartsWith("X"))
{
x = float.Parse(ExtractNumbers(n.Value));
x = x * 1000;
x_code = Convert.ToInt32(x);
}
if (n.Value.StartsWith("Y"))
{
y = float.Parse(ExtractNumbers(n.Value));
y = y * 1000;
y_code = Convert.ToInt32(y);
}
if (n.Value.StartsWith("Z"))
{
z = float.Parse(ExtractNumbers(n.Value));
z = z * 1000;
z_code = Convert.ToInt32(z);
}
}
ExchangeInputAndOutputReports(g_code,x_code, y_code,z_code);
}