原生的TextBox不支持文本的垂直居中及Padding功能,今天晚上抽时间搞了一下,此代码主要为增加这些功能。与大家共享。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace TextBoxEx
{
public partial class TextBoxEx : TextBox
{
//设置Rect消息
private const int EM_SETRECT = 179;
//获取Rect消息
private const int EM_GETRECT = 178;
//private const int WM_GETTEXT = 0x000d;
//private const int WM_COPY = 0x0301;
//粘贴消息
private const int WM_PASTE = 0x0302;
//绘制消息
private const int WM_PAINT = 0xF;
//控件颜色编辑消息
private const int WM_CTLCOLOREDIT = 0x0133;
//private const int WM_CONTEXTMENU = 0x007B;
//private const int WM_RBUTTONDOWN = 0x0204;
public TextBoxEx()
{
InitializeComponent();
//this.SetStyle(ControlStyles.UserPaint
// | ControlStyles.DoubleBuffer
// | ControlStyles.ResizeRedraw //调整大小时重绘
// | ControlStyles.AllPaintingInWmPaint // 禁止擦除背景.
// | ControlStyles.OptimizedDoubleBuffer // 双缓冲
// | ControlStyles.SupportsTransparentBackColor //透明效果
// , true);
//多行显示 只有多行显示才能设置Rect有效
this.Multiline = true;
//不允许回国
AllowReturn = false;
//关闭默认的边框
BorderStyle = System.Windows.Forms.BorderStyle.None;
//禁止折行
WordWrap = false;
_textMargin = new Padding(1);
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
SetTextDispLayout();
}
protected override void OnTextAlignChanged(EventArgs e)
{
base.OnTextAlignChanged(e);
SetTextDispLayout();
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
//如果不允许回车 屏蔽回车 换行键值
if (!AllowReturn
&& ((int)e.KeyChar == (int)Keys.Return || (int)e.KeyChar == (int)Keys.LineFeed))
{
e.Handled = true