在 http://www.codeproject.com/KB/edit/AlphaBlendedTextControls.aspx 的基础上增加了水印文字

代码如下:

  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
  public class win32
{ public const int WM_MOUSEMOVE = 0x0200;
public const int WM_LBUTTONDOWN = 0x0201;
public const int WM_LBUTTONUP = 0x0202;
public const int WM_RBUTTONDOWN = 0x0204;
public const int WM_LBUTTONDBLCLK = 0x0203; public const int WM_MOUSELEAVE = 0x02A3; public const int WM_PAINT = 0x000F;
public const int WM_ERASEBKGND = 0x0014; public const int WM_PRINT = 0x0317; //const int EN_HSCROLL = 0x0601;
//const int EN_VSCROLL = 0x0602; public const int WM_HSCROLL = 0x0114;
public const int WM_VSCROLL = 0x0115; public const int EM_GETSEL = 0x00B0;
public const int EM_LINEINDEX = 0x00BB;
public const int EM_LINEFROMCHAR = 0x00C9; public const int EM_POSFROMCHAR = 0x00D6; [DllImport("USER32.DLL", EntryPoint = "PostMessage")]
public static extern bool PostMessage(IntPtr hwnd, uint msg,
IntPtr wParam, IntPtr lParam); /*
BOOL PostMessage( HWND hWnd,
UINT Msg,
WPARAM wParam,
LPARAM lParam
);
*/ // Put this declaration in your class //IntPtr
[DllImport("USER32.DLL", EntryPoint = "SendMessage")]
public static extern int SendMessage(IntPtr hwnd, int msg, IntPtr wParam,
IntPtr lParam); [DllImport("USER32.DLL", EntryPoint = "GetCaretBlinkTime")]
public static extern uint GetCaretBlinkTime(); const int WM_PRINTCLIENT = 0x0318; const long PRF_CHECKVISIBLE = 0x00000001L;
const long PRF_NONCLIENT = 0x00000002L;
const long PRF_CLIENT = 0x00000004L;
const long PRF_ERASEBKGND = 0x00000008L;
const long PRF_CHILDREN = 0x00000010L;
const long PRF_OWNED = 0x00000020L; /* Will clean this up later doing something like this
enum CaptureOptions : long
{
PRF_CHECKVISIBLE= 0x00000001L,
PRF_NONCLIENT = 0x00000002L,
PRF_CLIENT = 0x00000004L,
PRF_ERASEBKGND = 0x00000008L,
PRF_CHILDREN = 0x00000010L,
PRF_OWNED = 0x00000020L
}
*/ public static bool CaptureWindow(System.Windows.Forms.Control control,
ref System.Drawing.Bitmap bitmap)
{
//This function captures the contents of a window or control Graphics g2 = Graphics.FromImage(bitmap); //PRF_CHILDREN // PRF_NONCLIENT
int meint = (int)(PRF_CLIENT | PRF_ERASEBKGND); //| PRF_OWNED ); // );
System.IntPtr meptr = new System.IntPtr(meint); System.IntPtr hdc = g2.GetHdc();
win32.SendMessage(control.Handle, win32.WM_PRINT, hdc, meptr); g2.ReleaseHdc(hdc);
g2.Dispose(); return true; } }

另外一个透明textbox如下 http://www.codeproject.com/KB/edit/alphablendtextbox.aspx

效果图:

c#透明TextBox的更多相关文章

  1. 解决winfrom下TextBox不支持透明背景色

    不知道微软扯什么拉鸡蛋子,居然有控件不支持透明,我实在想喷设计的人脑残.尤其可恨的是TextBox不支持,更可恨的是直到最新版.net4.6也不支持.源码又看不见,具体实现细节都不知道,谁能改得动?这 ...

  2. TextBox自定义控件

    首先来一发图: 今天主要说的textBox内部给予提示: 使用自定义控件方式:TextBoxTip继承TextBox 利用TextBox的背景画刷功能 VisualBrush是一种比较特殊的笔刷,它的 ...

  3. C# Winform实现炫酷的透明动画界面

    做过.NET Winform窗体美化的人应该都很熟悉UpdateLayeredWindow吧,UpdateLayeredWindow可以实现窗体的任意透明,效果很好,不会有毛边.不过使用这个API之后 ...

  4. 继承control的自定义TextBox

    继承control的自定义TextBox 下面来介绍一下本人写的一个自定义的textbox,首先说一下写这个控件遇到的几个难点:第一.关联输入法:第二.画字符串和焦点线 先随便上两张效果图吧: 下面这 ...

  5. UWP TextBox私人定制

    这次私人定制的是背景透明的TextBox,普通的TextBox在获取焦点后,背景色就变白色了. 下面的代码可以让TextBox的背景始终是透明的. 其实很简单,就修改了 <Setter Prop ...

  6. 关于WPF中TextBox使用SelectAll无效的问题的解决办法

    1.首先保证你设置的SelectionBrush不是透明的颜色或者和背景色相同 2.在使用SelectAll之前要保证Textox以及获取到焦点. this.textbox.SelectionBrus ...

  7. WPF 透明掩码 OpactiyMask

    原文:WPF 透明掩码 OpactiyMask 在WPF中提供了Opacity属性使得元素的所有内容都是透明的.而OpacityMask属性可以使元素的特定区域变成透明. OpacityMask属性接 ...

  8. 如何在WPF控件上应用简单的褪色透明效果?

    原文 https://dailydotnettips.com/how-to-create-simple-faded-transparent-controls-in-wpf/ 使用OpacityMask ...

  9. 【WPF学习】第四十二章 透明

    WPF支持真正的透明效果.这意味着,如果在一个性质或元素上层叠另外几个形状或元素,并让所有这些形状和元素具有不同的透明度,就会看到所期望的效果.通过该特性能够创建透过上面的元素可以看到的的图像背景,这 ...

随机推荐

  1. 【t095】拯救小tim

    Time Limit: 1 second Memory Limit: 128 MB [问题描述] 小tim在游乐场,有一天终于逃了出来!但是不小心又被游乐场的工作人员发现了... 所以你的任务是安全地 ...

  2. OpenVZ安装指南,一种操作系统级别的虚拟化技术

    鼎鼎大名的 OpenVZ 谁不知道?在主机行业被使用(滥用)很多年,依然在茁壮发展.作为一种操作系统级别的虚拟化技术,运行 OpenVZ 没有硬性的硬件要求.OpenVZ 能够创建被称为容器(cont ...

  3. sql知识收藏小总结

    div { background-color: #eee; border-radius: 3px; border: 1px solid #999; padding: 4px; display: blo ...

  4. 从Client应用场景介绍IdentityServer4(三)

    原文:从Client应用场景介绍IdentityServer4(三) 在学习其他应用场景前,需要了解几个客户端的授权模式.首先了解下本节使用的几个名词 Resource Owner:资源拥有者,文中称 ...

  5. 51系列小型操作系统精髓 简单实现6 C语言版待改进

    #include "STC12C5A.H" #define TIMER_RELOAD()  {TL0=0x00;TH0=0xC4;}//使能T/C  初始10ms #define ...

  6. javaS的tring和androidS的tring区别是什么?

    这是今天阿里电话面试被问到的,在之前确实没有想过(一直以为是一样的),于是面试完之后,我立即打开了源代码,对这两个String类进行了比較,以下是我的发现. 首先我观察了这两个String类所导入的包 ...

  7. Qt - QDialog,QWidget实现模态及非模态(模态Widget不能有父窗口,如果设置无边框就不能阻塞父窗口,但是可以强行设置指定Qt::Dialog,还可以setAttribute(Qt::WA_ShowModal),很多讲究)good

    在Qt中QDialog为“窗口”,而QWidget为“部件”,首先还是了解下<Qt 窗口与部件的概念>. 对于 QDialog 的模态及非模态是直接可以实现的,很多课本中都会提到,此处总结 ...

  8. keras 的使用

    theano 以及 TensorFlow 是 keras 的 backend(后端支持),因此,keras 本质上是对 thenao 或者 TensorFlow 的进一步封装(wrapper). ke ...

  9. crossplatform---Nodejs in Visual Studio Code 03.学习Express

    1.开始 下载源码:https://github.com/sayar/NodeMVA Express组件:npm install express -g(全局安装) 2.ExpressRest 打开目录 ...

  10. OpenGL(八) 显示列表

    OpenGL在即时模式(Immediate Mode)下绘图时,程序中每条语句产生的图形对象被直接送进绘图流水线,在显示终端立即绘制出来.当需要在程序中多次绘制同一个复杂的图像对象时,这种即时模式会消 ...