首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

面试碰到的题目:手写一个WinForm程序,包含布局整齐的一个文本框和一个按钮,单击按钮弹出消息框显示文本框的内容,用委托实现。解决思路

2012-01-16 
面试碰到的题目:手写一个WinForm程序,包含布局整齐的一个文本框和一个按钮,单击按钮弹出消息框显示文本框

面试碰到的题目:手写一个WinForm程序,包含布局整齐的一个文本框和一个按钮,单击按钮弹出消息框显示文本框的内容,用委托实现。
我的写法是这样的:
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Collections.Generic;

public class WinFormDemo
{
  static void Main()
  {
  CreateMyForm();
  }

  public static void CreateMyForm()
  {
  Form form1 = new Form();

  //添加一个TextBox
  TextBox textBox1 = new TextBox();
  textBox1.Multiline = true;
  textBox1.ScrollBars = ScrollBars.Vertical;
  textBox1.AcceptsReturn = true;
  textBox1.AcceptsTab = true;
  textBox1.WordWrap = true;
  textBox1.Text = "Hello world!";
  textBox1.Name = "textBox1";
  textBox1.Location = new Point(10,10);

  //添加button1,单击它时显示textBox1的内容
  Button button1 = new Button();
  button1.Text = "Show";
  button1.Location = new Point(10, 40);
  button1.Click += new EventHandler(button1_Click);


  form1.AcceptButton = button1;
  form1.StartPosition = FormStartPosition.CenterScreen;
  form1.Controls.Add(button1);
  form1.Controls.Add(textBox1);
  form1.ShowDialog();
  }

  public static void button1_Click(Object sender,EventArgs e) 
  {
  Button button = (Button)sender;
  Form form = button.FindForm();
  MessageBox.Show(form.Controls["textBox1"].Text);
  }
}

[解决办法]

C# code
namespace MyApplication{    public partial class Form1 : Form    {        delegate void ShowText();        TextBox textBox1 = new TextBox();        Button button1 = new Button();        public Form1()        {            textBox1.Text = "出题的人很无聊...";            textBox1.Location = new Point((Width - textBox1.Width) / 3, (Height - textBox1.Height) / 3);            textBox1.Parent = this;            button1.Text = "button1";            button1.Location = new Point(textBox1.Left + textBox1.Width + 8, textBox1.Top);            button1.Click += new EventHandler(button1_Click);            button1.Parent = this;        }        void button1_Click(Object sender, EventArgs e)        {            Invoke(new ShowText(DoShowText));        }        void DoShowText()        {            MessageBox.Show(textBox1.Text);        }            }}
[解决办法]
手写比较强悍

热点排行