参考我以前回答的代码。代码如下:
//--------------------------------开始----------------------
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;namespace TextBoxOverWrite
{
/// <summary>
/// This sample has a textbox with an overwrite mode. A context menu is used to
/// set the overwrite property
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private OverWriteTextBox textBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;public Form1()
{
InitializeComponent();
}/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null) 
{
components.Dispose();
}
}
base.Dispose( disposing );
}#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBox1 = new OverWriteTextBox();
// 
// textBox1
// 
this.textBox1.Location = new System.Drawing.Point(104, 40);
this.textBox1.Name = "textBox1";
this.textBox1.TabIndex = 0;
this.textBox1.Text = "text";
// 
// Form1
// 
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(352, 229);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.textBox1});
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);}
#endregion/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main() 
{
Application.Run(new Form1());
} }public class OverWriteTextBox : TextBox
{
private bool _overWrite = false;public bool OverWrite
{
get { return _overWrite;}
set { _overWrite = value;}
}public OverWriteTextBox()
{
this.KeyPress += new KeyPressEventHandler(HandleKeyPress);
this.MouseDown += new MouseEventHandler(HandleMouseDown);this.ContextMenu = new ContextMenu();
MenuItem item = new MenuItem("OverWrite", new EventHandler(HandleOverWriteClick));
this.ContextMenu.MenuItems.Add(item);this.ContextMenu.Popup += new EventHandler(HandleContextPopup);
}private void HandleMouseDown(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{}
}private void HandleContextPopup(object sender, EventArgs e)
{
this.ContextMenu.MenuItems[0].Checked = OverWrite;
}private void HandleOverWriteClick(object sender, EventArgs e)
{
OverWrite = !OverWrite;
}private void HandleKeyPress(object sender, KeyPressEventArgs e)
{
if(OverWrite && this.SelectedText == "")
{
this.SelectionLength = 1;
}
}
}
}
//--------------结束------------------