(二十九)c#Winform自定义控件-文本框(二)
官网
前提
入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章。
GitHub:https://github.com/kwwwvagaa/NetWinformControl
码云:https://gitee.com/kwwwvagaa/net_winform_custom_control.git
如果觉得写的还行,请点个 star 支持一下吧
欢迎前来交流探讨: 企鹅群568015492 idkey=6e08741ef16fe53bf0314c1c9e336c4f626047943a8b76bac062361bab6b4f8d">
目录
https://www.cnblogs.com/bfyx/p/11364884.html
准备工作
终于到文本框了,文本框将包含原文本框扩展,透明文本框,数字输入文本框,带边框文本框
本文将讲解透明文本框
开始
这个用到的很少,直接看代码吧
// 版权所有 黄正辉 交流群:568015492 QQ:623128629
// 文件名称:TextBoxTransparent.cs
// 创建日期:2019-08-15 16:03:49
// 功能描述:TextBox
// 项目地址:https://gitee.com/kwwwvagaa/net_winform_custom_control
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms; using System.Drawing.Imaging; namespace HZH_Controls.Controls
{
public class TextBoxTransparent : TextBoxEx
{
#region private variables private uPictureBox myPictureBox;
private bool myUpToDate = false;
private bool myCaretUpToDate = false;
private Bitmap myBitmap;
private Bitmap myAlphaBitmap; private int myFontHeight = ; private System.Windows.Forms.Timer myTimer1; private bool myCaretState = true; private bool myPaintedFirstTime = false; private Color myBackColor = Color.White;
private int myBackAlpha = ; /// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null; #endregion // end private variables #region public methods and overrides public TextBoxTransparent()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// TODO: Add any initialization after the InitializeComponent call this.BackColor = myBackColor; this.SetStyle(ControlStyles.UserPaint, false);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.DoubleBuffer, true); myPictureBox = new uPictureBox();
this.Controls.Add(myPictureBox);
myPictureBox.Dock = DockStyle.Fill;
} protected override void OnResize(EventArgs e)
{ base.OnResize(e);
this.myBitmap = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height);//(this.Width,this.Height);
this.myAlphaBitmap = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height);//(this.Width,this.Height);
myUpToDate = false;
this.Invalidate();
} //Some of these should be moved to the WndProc later protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
myUpToDate = false;
this.Invalidate();
} protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
myUpToDate = false;
this.Invalidate(); } protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
myUpToDate = false;
this.Invalidate();
} protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
this.Invalidate();
} protected override void OnGiveFeedback(GiveFeedbackEventArgs gfbevent)
{
base.OnGiveFeedback(gfbevent);
myUpToDate = false;
this.Invalidate();
} protected override void OnMouseLeave(EventArgs e)
{
//found this code to find the current cursor location
//at http://www.syncfusion.com/FAQ/WinForms/FAQ_c50c.asp#q597q Point ptCursor = Cursor.Position; Form f = this.FindForm();
ptCursor = f.PointToClient(ptCursor);
if (!this.Bounds.Contains(ptCursor))
base.OnMouseLeave(e);
} protected override void OnChangeUICues(UICuesEventArgs e)
{
base.OnChangeUICues(e);
myUpToDate = false;
this.Invalidate();
} //--
protected override void OnGotFocus(EventArgs e)
{
base.OnGotFocus(e);
myCaretUpToDate = false;
myUpToDate = false;
this.Invalidate(); myTimer1 = new System.Windows.Forms.Timer(this.components);
myTimer1.Interval = (int)win32.GetCaretBlinkTime(); // usually around 500; myTimer1.Tick += new EventHandler(myTimer1_Tick);
myTimer1.Enabled = true; } protected override void OnLostFocus(EventArgs e)
{
base.OnLostFocus(e);
myCaretUpToDate = false;
myUpToDate = false;
this.Invalidate(); myTimer1.Dispose();
} //-- protected override void OnFontChanged(EventArgs e)
{
if (this.myPaintedFirstTime)
this.SetStyle(ControlStyles.UserPaint, false); base.OnFontChanged(e); if (this.myPaintedFirstTime)
this.SetStyle(ControlStyles.UserPaint, true); myFontHeight = GetFontHeight(); myUpToDate = false;
this.Invalidate();
} protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
myUpToDate = false;
this.Invalidate();
} protected override void WndProc(ref Message m)
{ base.WndProc(ref m); // need to rewrite as a big switch if (m.Msg == win32.WM_PAINT)
{ myPaintedFirstTime = true; if (!myUpToDate || !myCaretUpToDate)
GetBitmaps();
myUpToDate = true;
myCaretUpToDate = true; if (myPictureBox.Image != null) myPictureBox.Image.Dispose(); if (string.IsNullOrEmpty(this.Text) && !string.IsNullOrEmpty(this.PromptText))
{
Bitmap bit = (Bitmap)myAlphaBitmap.Clone();
Graphics g = Graphics.FromImage(bit);
SizeF sizet1 = g.MeasureString(this.PromptText, this.PromptFont);
g.DrawString(this.PromptText, this.PromptFont, new SolidBrush(PromptColor), new PointF(, (bit.Height - sizet1.Height) / ));
g.Dispose();
myPictureBox.Image = bit;
}
else
{
myPictureBox.Image = (Image)myAlphaBitmap.Clone();
}
} else if (m.Msg == win32.WM_HSCROLL || m.Msg == win32.WM_VSCROLL)
{
myUpToDate = false;
this.Invalidate();
} else if (m.Msg == win32.WM_LBUTTONDOWN
|| m.Msg == win32.WM_RBUTTONDOWN
|| m.Msg == win32.WM_LBUTTONDBLCLK
// || m.Msg == win32.WM_MOUSELEAVE ///****
)
{
myUpToDate = false;
this.Invalidate();
} else if (m.Msg == win32.WM_MOUSEMOVE)
{
if (m.WParam.ToInt32() != ) //shift key or other buttons
{
myUpToDate = false;
this.Invalidate();
}
} if (m.Msg == || m.Msg == || m.Msg == )
{
base.OnPaint(null);
} //System.Diagnostics.Debug.WriteLine("Pro: " + m.Msg.ToString("X")); } /// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
//this.BackColor = Color.Pink;
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
} #endregion //end public method and overrides #region public property overrides public new BorderStyle BorderStyle
{
get { return base.BorderStyle; }
set
{
if (this.myPaintedFirstTime)
this.SetStyle(ControlStyles.UserPaint, false); base.BorderStyle = value; if (this.myPaintedFirstTime)
this.SetStyle(ControlStyles.UserPaint, true); this.myBitmap = null;
this.myAlphaBitmap = null;
myUpToDate = false;
this.Invalidate();
}
} public new Color BackColor
{
get
{
return Color.FromArgb(base.BackColor.R, base.BackColor.G, base.BackColor.B);
}
set
{
myBackColor = value;
base.BackColor = value;
myUpToDate = false;
}
}
public override bool Multiline
{
get { return base.Multiline; }
set
{
if (this.myPaintedFirstTime)
this.SetStyle(ControlStyles.UserPaint, false); base.Multiline = value; if (this.myPaintedFirstTime)
this.SetStyle(ControlStyles.UserPaint, true); this.myBitmap = null;
this.myAlphaBitmap = null;
myUpToDate = false;
this.Invalidate();
}
} #endregion //end public property overrides #region private functions and classes private int GetFontHeight()
{
Graphics g = this.CreateGraphics();
SizeF sf_font = g.MeasureString("X", this.Font);
g.Dispose();
return (int)sf_font.Height;
} private void GetBitmaps()
{ if (myBitmap == null
|| myAlphaBitmap == null
|| myBitmap.Width != Width
|| myBitmap.Height != Height
|| myAlphaBitmap.Width != Width
|| myAlphaBitmap.Height != Height)
{
myBitmap = null;
myAlphaBitmap = null;
} if (myBitmap == null)
{
myBitmap = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height);//(Width,Height);
myUpToDate = false;
} if (!myUpToDate)
{
//Capture the TextBox control window this.SetStyle(ControlStyles.UserPaint, false); win32.CaptureWindow(this, ref myBitmap); this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.BackColor = Color.FromArgb(myBackAlpha, myBackColor); }
//-- Rectangle r2 = new Rectangle(, , this.ClientRectangle.Width, this.ClientRectangle.Height);
ImageAttributes tempImageAttr = new ImageAttributes(); //Found the color map code in the MS Help ColorMap[] tempColorMap = new ColorMap[];
tempColorMap[] = new ColorMap();
tempColorMap[].OldColor = Color.FromArgb(, myBackColor);
tempColorMap[].NewColor = Color.FromArgb(myBackAlpha, myBackColor); tempImageAttr.SetRemapTable(tempColorMap); if (myAlphaBitmap != null)
myAlphaBitmap.Dispose(); myAlphaBitmap = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height);//(Width,Height); Graphics tempGraphics1 = Graphics.FromImage(myAlphaBitmap); tempGraphics1.DrawImage(myBitmap, r2, , , this.ClientRectangle.Width, this.ClientRectangle.Height, GraphicsUnit.Pixel, tempImageAttr); tempGraphics1.Dispose(); //---- if (this.Focused && (this.SelectionLength == ))
{
Graphics tempGraphics2 = Graphics.FromImage(myAlphaBitmap);
if (myCaretState)
{
//Draw the caret
Point caret = this.findCaret();
Pen p = new Pen(this.ForeColor, );
tempGraphics2.DrawLine(p, caret.X + , caret.Y + , caret.X + , caret.Y + myFontHeight);
tempGraphics2.Dispose();
} } } private Point findCaret()
{
/* Find the caret translated from code at
* http://www.vb-helper.com/howto_track_textbox_caret.html
*
* and
*
* http://www.microbion.co.uk/developers/csharp/textpos2.htm
*
* Changed to EM_POSFROMCHAR
*
* This code still needs to be cleaned up and debugged
* */ Point pointCaret = new Point();
int i_char_loc = this.SelectionStart;
IntPtr pi_char_loc = new IntPtr(i_char_loc); int i_point = win32.SendMessage(this.Handle, win32.EM_POSFROMCHAR, pi_char_loc, IntPtr.Zero);
pointCaret = new Point(i_point); if (i_char_loc == )
{
pointCaret = new Point();
}
else if (i_char_loc >= this.Text.Length)
{
pi_char_loc = new IntPtr(i_char_loc - );
i_point = win32.SendMessage(this.Handle, win32.EM_POSFROMCHAR, pi_char_loc, IntPtr.Zero);
pointCaret = new Point(i_point); Graphics g = this.CreateGraphics();
String t1 = this.Text.Substring(this.Text.Length - , ) + "X";
SizeF sizet1 = g.MeasureString(t1, this.Font);
SizeF sizex = g.MeasureString("X", this.Font);
g.Dispose();
int xoffset = (int)(sizet1.Width - sizex.Width);
pointCaret.X = pointCaret.X + xoffset; if (i_char_loc == this.Text.Length)
{
String slast = this.Text.Substring(Text.Length - , );
if (slast == "\n")
{
pointCaret.X = ;
pointCaret.Y = pointCaret.Y + myFontHeight;
}
} } return pointCaret;
} private void myTimer1_Tick(object sender, EventArgs e)
{
//Timer used to turn caret on and off for focused control myCaretState = !myCaretState;
myCaretUpToDate = false;
this.Invalidate();
} private class uPictureBox : PictureBox
{
public uPictureBox()
{
this.SetStyle(ControlStyles.Selectable, false);
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.DoubleBuffer, true); this.Cursor = null;
this.Enabled = true;
this.SizeMode = PictureBoxSizeMode.Normal; } //uPictureBox
protected override void WndProc(ref Message m)
{
if (m.Msg == win32.WM_LBUTTONDOWN
|| m.Msg == win32.WM_RBUTTONDOWN
|| m.Msg == win32.WM_LBUTTONDBLCLK
|| m.Msg == win32.WM_MOUSELEAVE
|| m.Msg == win32.WM_MOUSEMOVE)
{
//Send the above messages back to the parent control
win32.PostMessage(this.Parent.Handle, (uint)m.Msg, m.WParam, m.LParam);
} else if (m.Msg == win32.WM_LBUTTONUP)
{
//?? for selects and such
this.Parent.Invalidate();
} base.WndProc(ref m);
} } // End uPictureBox Class #endregion // end private functions and classes #region Component 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()
{
components = new System.ComponentModel.Container();
}
#endregion #region New Public Properties [
Category("Appearance"),
Description("The alpha value used to blend the control's background. Valid values are 0 through 255."),
Browsable(true),
DesignerSerializationVisibility(DesignerSerializationVisibility.Visible) ]
public int BackAlpha
{
get { return myBackAlpha; }
set
{
int v = value;
if (v > )
v = ;
myBackAlpha = v;
myUpToDate = false;
Invalidate();
}
} #endregion } // End AlphaTextBox Class
}
用处及效果
用到的比较少,你高兴就用,哈哈
最后的话
如果你喜欢的话,请到 https://gitee.com/kwwwvagaa/net_winform_custom_control 点个星 星吧
(二十九)c#Winform自定义控件-文本框(二)的更多相关文章
- (三十)c#Winform自定义控件-文本框(三)
前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. 开源地址:https://gitee.com/kwwwvagaa/net_winform_custom_control ...
- (十六)c#Winform自定义控件-文本框哪里去了?-HZHControls
官网 http://www.hzhcontrols.com 前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. GitHub:https://github.com/kww ...
- (三十一)c#Winform自定义控件-文本框(四)
前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. 开源地址:https://gitee.com/kwwwvagaa/net_winform_custom_control ...
- (二十八)c#Winform自定义控件-文本框(一)
前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. 开源地址:https://gitee.com/kwwwvagaa/net_winform_custom_control ...
- (二十)c#Winform自定义控件-有后退的窗体
前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. 开源地址:https://gitee.com/kwwwvagaa/net_winform_custom_control ...
- 【二十九】php之简易微信二维码支付
参考二维码支付接口文档:https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=6_5 index.php <!DOCTYPE htm ...
- Bootstrap入门(二十九)JS插件6:弹出框
Bootstrap入门(二十九)JS插件6:弹出框 加入小覆盖的内容,像在iPad上,用于存放非主要信息 弹出框是依赖于工具提示插件的,那它也和工具提示是一样的,是需要初始化才能够使用的 首先我们引入 ...
- Bootstrap <基础二十九>面板(Panels)
Bootstrap 面板(Panels).面板组件用于把 DOM 组件插入到一个盒子中.创建一个基本的面板,只需要向 <div> 元素添加 class .panel 和 class .pa ...
- Web 开发人员和设计师必读文章推荐【系列二十九】
<Web 前端开发精华文章推荐>2014年第8期(总第29期)和大家见面了.梦想天空博客关注 前端开发 技术,分享各类能够提升网站用户体验的优秀 jQuery 插件,展示前沿的 HTML5 ...
随机推荐
- 学习4:内容# 1.列表 # 2.元祖 # 3.range
1.列表 列表 -- list -- 容器 有序,可变,支持索引 列表: 存储数据,支持的数据类型很多 字符串,数字,布尔值,列表,集合,元祖,字典, 定义一个列表 lst = ["dsb& ...
- 异常:带有 CLSID {} 的 COM 对象无效或未注册
今天处理调试打印程序的时候,看到这个异常: 代码: try { string strApplyEmpno=""; string strApplyDeptCode="&qu ...
- Python入门基础(9)__面向对象编程_2
__str__方法 如果在开发中,希望使用print输出对象变量时,能够打印自定义的内容,就可以利用__str__这个内置方法了 注意:__str__方法必须返回一个字符串 class Cat(): ...
- Spring_简单入门(学习笔记1)
Spring是一个分层的JavaSE/EE full-stack(一站式) 轻量级开源框架. 具体介绍参考 一:IoC(Inversion of Control)控制反转,将创建对象实例反转给spri ...
- Hadoop值Partition分区
分区操作 为什么要分区? 要求将统计结果按照条件输出到不同文件中(分区).比如:将统计结果按 照手机归属地不同省份输出到不同文件中(分区) 默认 partition 分区 /** 源码中:numRed ...
- 【译】WebAPI,Autofac,以及生命周期作用域
说明 原文地址:http://decompile.it/blog/2014/03/13/webapi-autofac-lifetime-scopes/ 介绍 这是一篇关于AutoFac的生命周期作用域 ...
- 【MySQL】(一)MySQL 体系结构和存储引擎
1.1.定义数据库和实例 数据库:物理操作系统文件或其他形式文件类型的集合.在MySQL数据库中,数据库文件可以是frm.MYD.MYI.ibd结尾的文件. 实例:MySQL数据库由后台线程以及一个共 ...
- MySQL常用工具、日志及读写分离
MySQL常用工具.日志及读写分离 1.MySQL中常用工具 1.1 mysql 1.1.1连接选项 1.1.2 执行选项 1.2 mysqladmin 1.3 mysqlbinlog 1.4 mys ...
- win7 开机网络等待,应用打不开的解决方案
状况描述:最近,笔记本电脑开机之后,网络图标一直转圈,任何应用程序也打不开,开机关机还是可以的,之前是偶尔发生这种情况,然后重启一下或许就行了,但最近每次开机都是这个情况,很恼火,在网上百度了很久,有 ...
- Intellij IDEA 出现“Usage of API documented as @since 1.8+”的解决办法
转自 https://blog.csdn.net/qq_27093465/article/details/69372028 具体报错内容如下: This inspection finds all us ...