日期:2014-05-18  浏览次数:20862 次

两道Winfrom题目,在此求教,希望给个思路或者代码
1。创建一个Winform程序,以随即方式显示移动的“好好学习”,“天天向上”信息。要求两行文本的移动不分先后,单独移动

2.设计一个Winform程序,从1加到1 000 000,用三个线程分段计算,累加和用一个变量表示,利用lock语句的锁定机制实现该功能。
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;
using System.Threading;

namespace WinformPro2012_2_20.Chapter8
{
  public partial class frmLock : Form
  {
  int sum;//保存累加的和  
  string txt = "1+2+3+...+1000000";
  delegate void AddCallListBack(string text);
  public frmLock()
  {
  InitializeComponent();
  }

  private void button1_Click(object sender, EventArgs e)
  {
  listBox1.Items.Clear();
  Thread t1 = new Thread(new ThreadStart(Calculate));
  Thread t2 = new Thread(new ThreadStart(Calculate));
  Thread t3 = new Thread(new ThreadStart(Calculate));
  t1.Start();
  t2.Start();
  t3.Start();

  }
  private void Calculate()
  {
  lock (this)
  {
  for (int i = 1; i < 1000001; i++)
  {
  sum += i;
  }
  Start(string.Format("{0}={1}", txt, sum.ToString()));
  }
  }
  private void Start(string text)
  {
  if (listBox1.InvokeRequired)
  {
  AddCallListBack add = new AddCallListBack(Start);
  this.Invoke(add, new object[] { text });
  }
  else
  listBox1.Items.Add(text);

  }
  }
}
第二题没有达到要求,不知道该怎么办了。

------解决方案--------------------
1。创建一个Winform程序,以随即方式显示移动的“好好学习”,“天天向上”信息。要求两行文本的移动不分先后,单独移动
 
新建一个label,用来显示信息
定义两个随机数x和y,一个从0到formName.Height-lbl.Height,一个从0到formName.Width-lbl.Width,分别用来定义label的Location.X和Location.Y
新建一个Timer,窗体初始化时设置为启用,Interval设置为1000(1秒)
在Timer的Ticker事件中重定向label的Location
lbl.Location = new Point(x,y);
------解决方案--------------------
这样行不行?
public partial class Form1 : Form
{
private long sum;
private static readonly object obj = new object();

public Form1()
{
InitializeComponent();
settext += new settexthandle( Form1_settext );
setbtnText += new setbuttonTextHandle( Form1_setbtnText );
}

void Form1_setbtnText( string s )
{
button1.Text = s;
}

void Form1_settext( string s )
{
button1.Invoke( setbtnText , s );
}

private delegate void settexthandle( string s );
private event settexthandle settext;

private delegate void setbuttonTextHandle( string s );
private event setbuttonTextHandle setbtnText;


private void button1_Click( object sender , EventArgs e )
{
sum = 0;
Thread th1 = new Thread( new ThreadStart( loop1 ) );
Thread th2 = new Thread( new ThreadStart( loop2 ) );
Thread th3 = new Thread( new ThreadStart( loop3 ) );
th1.Start();
th2.Start();