如果在同一台电脑上,必须实现两个application间通信时,又不想用UDP和TCP等协议,可以用文本来代替。可以用Timer来巧妙的实现,实现代码既简单又高效。我在程序中设计了两个Timer,第一个用来计算次数,第二个用来接受信息。其中第二个从开始就一直设置为True,例如代码如下:
timer2.Enabled = true;
其中第一个Timer代码如下,只要用来设置时间间隔和计量次数,代码如下:
private void timer1_Tick(object sender, EventArgs e) { if(time == 1) { timer1.Interval = 1500; counter++; textBox1.Text = Convert.ToString(counter); if(counter > 9) { timer1.Enabled = false; textBox2.Text = "INC : Increasing "; StreamWriter aw = new StreamWriter("d://c.text"); aw.WriteLine("2"); aw.Close(); } //In timer1 digital growth } else if(time == 2) { timer1.Interval = 2000; counter--; textBox1.Text = Convert.ToString(counter); while (counter < 0) { StreamWriter aw = new StreamWriter("d://c.text"); aw.WriteLine("8"); aw.Close(); Close(); } //In timer1 digital reduce } }
第二个Timer是用来接受信息的,就是用来代替Socket等套接字的。它的代码如下:
private void timer2_Tick(object sender, EventArgs e) { if(File.Exists(@"d://d.text")) { //Whether have the information the file using (StreamReader ar = new StreamReader("d://d.text")) { string line; if((line =ar.ReadLine()) != null) { num = Convert.ToInt32(line); ar.Close(); //Read in information } } switch (num) //According to information change { case 0: btnClose_Click(sender, e); Close(); break; case 1: textBox2.Text = "INC & DEC: Decreasing"; timer1.Enabled = true; time = 2; break; case 2: timer1.Enabled = false; btnStart.Enabled = true; btnStop.Enabled = false; textBox2.Text = "INC & DEC: Stop Increasing "; break; case 3: btnStop.Enabled = false; textBox2.Text = "INC :Stop Increasing "; break; case 4: btnStop.Enabled = true; textBox2.Text = "INC :Increasing "; break; case 5: btnStop.Enabled = false; btnStart.Enabled = true; timer1.Enabled = false; textBox2.Text = "INC & DEC:Stop Decreasing "; break; case 6: num = 0; counter = 0; textBox1.Text = "0"; textBox2.Text = "Initial state "; btnClose.Enabled = true; btnStart.Enabled = true; btnStop.Enabled = false; btnReset.Enabled = false; timer1.Enabled = false; time = 1; break; default: break; } File.Delete(@"d://d.text"); // Delete information file } } } }