自定义控件之WinForm中透明Label

归类于C# 参与评论

WinForm中并没有真正的透明Label,所以我们需要一个自定义控件来创建透明的Label,关键代码如下,这个代码是两年前我不记得从哪里找到的了。今天又看到了,所以记录下来。也许会用得到。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace Lyjt.Highway.Monitoring.bin
{
public partial class 透明Label : UserControl
{
#region Local Variables

public enum ShapeBorderStyles
{
ShapeBSNone,
ShapeBSFixedSingle,
};

private ShapeBorderStyles _borderStyle = ShapeBorderStyles.ShapeBSNone;
private System.Drawing.Color _backColor = Color.Black;
private System.Drawing.Color _borderColor = Color.White;
private int _radius = 20;
private int _opacity = 125;
private string _text = “doaTransparentLabel”;

//  Local Variables for text
public enum TextAlignment
{
Left,
Center,
Right
};

public enum MoveType
{
None,
RightToLeft,
DownToUp,
LeftToRight,
UpToDown
}

protected TextAlignment _textAlign = TextAlignment.Center;
protected MoveType _moving = MoveType.None;
protected bool _isSelected = false;
private System.Drawing.Color _dimmedColor = Color.LightGray;

// Work Variables
protected int pointX = 0;
protected int pointY = 0;
protected Rectangle iRect = new Rectangle();
protected Rectangle txtRect = new Rectangle();

#endregion

#region Constructor
public 透明Label()
{
InitializeComponent();
base.BackColor = Color.Transparent;
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.UserPaint, true);
SetStyle(ControlStyles.Opaque, false);
UpdateStyles();
this.components = new System.ComponentModel.Container();
this.timer1 = new System.Windows.Forms.Timer(this.components);
//
// timer1
//
this.timer1.Enabled = false;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
this.timer1.Interval = 100;
}
#endregion

#region Properties

[DefaultValue(typeof(Color), "Black")]
public new Color BackColor
// Gets or sets the background color of the control.
{
get { return _backColor; }
set { _backColor = value; Invalidate(); }
}

[
Bindable(true),
Category("Appearance"),
DefaultValue(ShapeBorderStyles.ShapeBSNone),
Description("Style of border to be drawn around control")
]
public ShapeBorderStyles ShapeBorderStyle
{
get { return _borderStyle; }
set { _borderStyle = value; this.Invalidate(); }
}

[DefaultValue(typeof(Color), "White"), Category("Appearance"), Description("The border color of the control.")]
/// Gets or sets the outer border color of the control.
public Color BorderColor
{
get { return _borderColor; }
set { _borderColor = value; Invalidate(); }
}

[
Bindable(true),
Category("Appearance"),
DefaultValue(125),
Description("The alpha value used to blend the control's background. Valid values are 0 through 255.")
]
public int Opacity
{
get { return _opacity; }
set { _opacity = value; this.Invalidate(); }
}

[
Bindable(true),
Category("Layout"),
DefaultValue(20),
Description("Radius of rounded borders")
]
public int Radius
{
get { return _radius; }
set { _radius = value; this.Invalidate(); }
}

[
Bindable(true),
Category("Appearance"),
DefaultValue("DOATransparentLabel"),
Description("Text in the DOATransparentLabel")
]
public String Caption
{
get { return _text; }
set { _text = value; this.Invalidate(); }
}

public override Font Font
{
get { return base.Font; }
set { base.Font = value; this.Invalidate(); }
}

public override Color ForeColor
{
get { return base.ForeColor; }
set { base.ForeColor = value; this.Invalidate(); }
}

[
Bindable(true),
Category("Appearance"),
Description("Dimmed Color"),
]
public Color DimmedColor
{
get { return _dimmedColor; }
set { _dimmedColor = value; this.Invalidate(); }
}

[
Bindable(true),
Category("Behavior"),
Description("Text movement"),
DefaultValue(MoveType.None)
]
public MoveType Moving
{
get { return _moving; }
set { _moving = value; this.Invalidate(); }
}

[
Bindable(true),
Category("Appearance"),
Description("Text alignment (Left, Right or Center), only with Moving None"),
DefaultValue(TextAlignment.Center)
]
public TextAlignment TextAlign
{
get { return _textAlign; }
set { _textAlign = value; this.Invalidate(); }
}

[
Bindable(true),
Category("Behavior"),
Description("Active the text movement"),
DefaultValue(false)
]
public bool MovingActive
{
get { return this.timer1.Enabled; }
set
{
if (value == false) _moving = MoveType.None;
this.timer1.Enabled = value;
this.Invalidate();
}
}

#endregion

#region Methods

protected override void OnPaint(PaintEventArgs e)
{
SmoothingMode sm = e.Graphics.SmoothingMode;
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
if (_borderStyle == ShapeBorderStyles.ShapeBSFixedSingle)
DrawBorder(e.Graphics);
DrawLabelBackground(e.Graphics);
DrawText(e);
e.Graphics.SmoothingMode = sm;
}

private void DrawBorder(Graphics g)
{
Rectangle rect = this.ClientRectangle;
rect.Width–;
rect.Height–;
using (GraphicsPath bp = GetPath(rect, _radius))
{
using (Pen p = new Pen(_borderColor))
{
g.DrawPath(p, bp);
}
}
}

private void DrawLabelBackground(Graphics g)
{
Rectangle rect = this.ClientRectangle;
iRect = rect;
rect.X++;
rect.Y++;
rect.Width -= 2;
rect.Height -= 2;
using (GraphicsPath bb = GetPath(rect, _radius))
{
using (Brush br = new SolidBrush(Color.FromArgb(_opacity, _backColor)))
{
g.FillPath(br, bb);
}
}
}

protected GraphicsPath GetPath(Rectangle rc, int r)
//  Build the path with the round corners in the rectangle
//  r is the radious of rounded corner.
{
int x = rc.X, y = rc.Y, w = rc.Width, h = rc.Height;
r = r << 1;
GraphicsPath path = new GraphicsPath();
if (r > 0)
//  If the radious of rounded corner is greater than one side then
//  do the side rounded
{
if (r > h) { r = h; };                              //Rounded
if (r > w) { r = w; };                              //Rounded
path.AddArc(x, y, r, r, 180, 90);                    //Upper left corner
path.AddArc(x + w – r, y, r, r, 270, 90);            //Upper right corner
path.AddArc(x + w – r, y + h – r, r, r, 0, 90);        //Lower right corner
path.AddArc(x, y + h – r, r, r, 90, 90);            //Lower left corner
path.CloseFigure();
}
else
//  If the radious of rounded corner is zero then the path is a rectangle
{
path.AddRectangle(rc);
}

return path;
}

protected void DrawText(PaintEventArgs pe)
{
//This is a workaround to get MeasureString to work properly
//pe.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
SizeF sz = pe.Graphics.MeasureString(_text, base.Font);
switch (_moving)
{
case MoveType.None:
NoMove();
break;
case MoveType.RightToLeft:
MoveRightToLeft();
break;
case MoveType.DownToUp:
MoveDownToUp();
break;
case MoveType.LeftToRight:
MoveLeftToRight();
break;
case MoveType.UpToDown:
MoveUpToDown();
break;
}
//Rectangle bounds for the text
txtRect = new Rectangle(this.pointX, this.pointY,
(int)sz.Width + 1, (int)sz.Height);

//If the mouse is passing over the text it is selected and will be dimmed
//otherwise nothing.
Brush brText = new SolidBrush(base.ForeColor);
Brush brTextDimmed = new SolidBrush(_dimmedColor);
if (_isSelected)
pe.Graphics.DrawString(_text,
base.Font,
brTextDimmed,
txtRect);
else
pe.Graphics.DrawString(_text,
base.Font,
brText,
txtRect);
}

protected void NoMove()
{
//Align text
switch (_textAlign)
{
case TextAlignment.Left:
pointX = (int)this.iRect.X;
break;
case TextAlignment.Center:
pointX = (this.iRect.Width – this.txtRect.Width) / 2;
break;
case TextAlignment.Right:
pointX = (this.iRect.Width – this.txtRect.Width);
break;
}
pointY = (this.iRect.Height – this.txtRect.Height) / 2;
}

protected void MoveRightToLeft()
{
if (pointX < -this.txtRect.Width)
{ pointX = this.iRect.X + this.iRect.Width; }
else
{ pointX -= 2; }
pointY = (this.iRect.Height – this.txtRect.Height) / 2;
}

protected void MoveDownToUp()
{
pointX = (this.iRect.Width – this.txtRect.Width) / 2;
if (pointY < -this.txtRect.Height)
{ pointY = (int)this.iRect.Y + this.iRect.Height; }
else
{ pointY -= 2; }
}

protected void MoveLeftToRight()
{
if (pointX > this.iRect.X + this.iRect.Width)
{ pointX = this.iRect.X – this.txtRect.Width; }
else
{ pointX += 2; }
pointY = (this.iRect.Height – this.txtRect.Height) / 2;
}

protected void MoveUpToDown()
{
pointX = (this.iRect.Width – this.txtRect.Width) / 2;
if (pointY > this.iRect.Y + this.iRect.Height)
{ pointY = (int)this.iRect.Y – this.iRect.Height; }
else
{ pointY += 2; }
}

protected override void OnMouseEnter(EventArgs e)
{
base.OnMouseEnter(e);
_isSelected = true;
this.Invalidate();
}

protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
_isSelected = false;
this.Invalidate();
}

private void timer1_Tick(object sender, System.EventArgs e)
{
this.Invalidate();
this.Update();
}

#endregion
}
}

winform相对路径和绝对路径 各种操作详解

归类于C# 参与评论

相对路径获取
string   path   =   System.IO.Directory.GetCurrentDirectory();//获取应用程序的当前工作目录。
string   str1   =   Application.StartupPath;//获取启动了应用程序的可执行文件的路径,不包括可执行文件的名称
string   str2   =   Application.ExecutablePath;//获取启动了应用程序的可执行文件的路径,包括可执行文件的名称。
string   str3   =   Environment.CurrentDirectory;//获取和设置当前目录(即该进程从中启动的目录)的完全限定路径。

System.Reflection.Assembly   ass=   System.Reflection.Assembly.GetExecutingAssembly();//获取当前代码正从中运行的   Assembly
string   strConfigLoc=ass.Location;//如果包含清单的已加载文件没有被影像复制,则获取该文件的基本代码格式的位置
FileInfo   FileInfoObj=   new   FileInfo(strConfigLoc);
strConfigLoc=FileInfoObj.DirectoryName;
MessageBox.Show(strConfigLoc);

C# Winform中如何获取文件路径

获取文件名方法:

用System.IO.Path.GetFileName和System.IO.Path.GetFileNameWithoutExtension(无扩展名)的方法

获取文件路径方法:

//获取当前进程的完整路径,包含文件名(进程名)。
string str = this.GetType().Assembly.Location;
result: X:\xxx\xxx\xxx.exe (.exe文件所在的目录+.exe文件名)

//获取新的 Process 组件并将其与当前活动的进程关联的主模块的完整路径,包含文件名(进程名)。
string str = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
result: X:\xxx\xxx\xxx.exe (.exe文件所在的目录+.exe文件名)

//获取和设置当前目录(即该进程从中启动的目录)的完全限定路径。
string str = System.Environment.CurrentDirectory;
result: X:\xxx\xxx (.exe文件所在的目录)

//获取当前 Thread 的当前应用程序域的基目录,它由程序集冲突解决程序用来探测程序集。
string str = System.AppDomain.CurrentDomain.BaseDirectory;
result: X:\xxx\xxx\ (.exe文件所在的目录+”\”)

//获取和设置包含该应用程序的目录的名称。
string str = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
result: X:\xxx\xxx\ (.exe文件所在的目录+”\”)

//获取启动了应用程序的可执行文件的路径,不包括可执行文件的名称。
string str = System.Windows.Forms.Application.StartupPath;
result: X:\xxx\xxx (.exe文件所在的目录)

//获取启动了应用程序的可执行文件的路径,包括可执行文件的名称。
string str = System.Windows.Forms.Application.ExecutablePath;
result: X:\xxx\xxx\xxx.exe (.exe文件所在的目录+.exe文件名)

//获取应用程序的当前工作目录(不可靠)。
string str = System.IO.Directory.GetCurrentDirectory();
result: X:\xxx\xxx (.exe文件所在的目录)

C# 获取路径中,文件名、目录、扩展名等

string path = “C:\\dir1\\dir2\\foo.txt”;
string str = “GetFullPath:” + Path.GetFullPath(path) + “\r\n”;
str += “GetDirectoryName:” + Path.GetDirectoryName(path) + “\r\n”;
str += “GetFileName:” + Path.GetFileName(path) + “\r\n”;
str += “GetFileNameWithoutExtension:” + Path.GetFileNameWithoutExtension(path) + “\r\n”;
str += “GetExtension:” + Path.GetExtension(path) + “\r\n”;
str += “GetPathRoot:” + Path.GetPathRoot(path) + “\r\n”;
MessageBox.Show(str);

结果:
GetFullPath:C:\dir1\dir2\foo.txt
GetDirectoryName:C:\dir1\dir2
GetFileName:foo.txt
GetFileNameWithoutExtension:foo
GetExtension:.txt
GetPathRoot:C:\

这里要说明 path 是如何C# 轻松获取路径中文件名、目录、扩展名等判断目录和文件名的:它把最后一个 \ 后面的内容当作是文件名。 // 内容来自js4j.com//

  • C:\dir1\dir2\foo.txt 文件名是 foo.txt,目录名是 C:\dir1\dir2。
  • C:\dir1\dir2\ 文件名是零长度字符串,目录名是 C:\dir1\dir2。
  • C:\dir1\dir2 文件名是 dir2,目录名是 C:\dir1。

VS2008调试快捷键【收集整理】

归类于C# 参与评论

F6: 生成解决方案

Ctrl+F6: 生成当前项目

F7: 查看代码

Shift+F7: 查看窗体设计器

F5: 启动调试

Ctrl+F5: 开始执行(不调试)

Shift+F5: 停止调试

Ctrl+Shift+F5: 重启调试

F9: 切换断点

Ctrl+F9: 启用/停止断点

Ctrl+Shift+F9: 删除全部断点

F10: 逐过程

Ctrl+F10: 运行到光标处

F11: 逐语句

Ctrl+K+D: 代码快速格式化

顶部