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

面试碰到的题目:手写一个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);
        }        
    }
}

------解决方案--------------------
手写比较强悍

相关资料更多>