WinForm代码收藏和演示
WinForm代码收藏和演示
DataGridView
WinForm中DataGridView控件的缺省复制功能按HTML格式存储到剪贴板,中文信息也许不会被其他程序识别为正确的编码格式,比如,在Word或者Excel中粘贴,汉字被变成乱码。下面的方法,是写一个继承自DataGridView控件的类MyDataGridView,将复制功能重写为以Unicode编码方式复制DataGridView内容,并公开一个CmdCopy方法,实现简单复制调用。
MyDataGridView加入了两个属性:RowNumberStart属性,设置或获取界面的起始行号;RowNumberEnabled属性,设置或获取是否绘制界面行号。绘制行号功能是重写的OnRowPostPaint方法实现的,因此重新设定后需要Refresh界面后才会使效果生效。
using System.ComponentModel; using System.Drawing; using System.Security.Permissions; using System.Windows.Forms; namespace Oyi319.WinFroms.Controls { public class MyDataGridView : DataGridView { private int _rowNumberStart = 1; [DefaultValue(1), Description("显示起始行号")] public virtual int RowNumberStart { get { return _rowNumberStart; } set { _rowNumberStart = value; } } [DefaultValue(false), Description("是否显示行号")] public virtual bool RowNumberEnabled { get; set; } protected override void OnRowPostPaint(DataGridViewRowPostPaintEventArgs e) { if (RowNumberEnabled) { var rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, RowHeadersWidth - 4, e.RowBounds.Height); TextRenderer.DrawText(e.Graphics, (e.RowIndex + RowNumberStart).ToString(), RowHeadersDefaultCellStyle.Font, rectangle, RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right); } base.OnRowPostPaint(e); } [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] protected override bool ProcessDataGridViewKey(KeyEventArgs e) { switch (e.KeyCode) { case Keys.Insert: case Keys.C: return ProcessInsertKey(e.KeyData); default: break; } return base.ProcessDataGridViewKey(e); } [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] private new bool ProcessInsertKey(Keys keyData) { if ((((keyData & (Keys.Alt | Keys.Control | Keys.Shift)) == Keys.Control) || (((keyData & (Keys.Alt | Keys.Control | Keys.Shift)) == (Keys.Control | Keys.Shift)) && ((keyData & Keys.KeyCode) == Keys.C))) && (ClipboardCopyMode != DataGridViewClipboardCopyMode.Disable)) { var clipboardContent = GetClipboardContent(); if (clipboardContent != null) { CmdCopy(); return true; } } return false; } /// <summary> /// 复制选中内容 /// </summary> public virtual void CmdCopy() { var clipboardContent = GetClipboardContent(); if (clipboardContent != null) { Clipboard.SetText(clipboardContent.GetData(DataFormats.UnicodeText).ToString()); } } } }
演示:
下载:
类型 : 7Z 压缩文件
大小 : 10 KB
ListBox
这是一个为ListBox项目重新绘制的例子。我们重新绘制控件,将它的DrawMode属性设置为OwnerDrawFixed(所有条目使用固定大小)或者OwnerDrawVariable。然后重写或者编写其DrawItem事件处理代码。
listBox1.DrawMode = DrawMode.OwnerDrawFixed; listBox1.DrawItem += ListBox1DrawItem;
void ListBox1DrawItem(object sender, DrawItemEventArgs e) { ListBox listBox = (ListBox)sender; if (e.Index < 0 || listBox.Items.Count == 0) return; //reutrn Brush brush = e.Index % 2 == 0 ? Brushes.LightYellow : Brushes.LightGreen; e.DrawBackground(); if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) { //e.DrawFocusRectangle(); e.Graphics.FillRectangle(Brushes.HotPink, e.Bounds); e.Graphics.DrawRectangle(new Pen(Color.DeepPink), e.Bounds); } else { e.Graphics.FillRectangle(brush, e.Bounds); } string displayText = string.Format("{1:N2}\n({0:G})", DateTime.Now, listBox.Items[e.Index]); Font font = e.Font; SizeF sizef = e.Graphics.MeasureString(displayText, font); listBox.ItemHeight = (int)sizef.Height; e.Graphics.DrawString(displayText, font, new SolidBrush(e.ForeColor), 20 + e.Bounds.Left, e.Bounds.Top); Image image = Image.FromFile("3_oyi319.jpg"); e.Graphics.DrawImage(image, new RectangleF(2 + e.Bounds.Left, (sizef.Height - 16) / 2 + e.Bounds.Top, 16, 16)); }
使用GDI+绘制界面的时候,可以更随意一点儿。它的演示效果如下图:
下载:
类型 : 7Z 压缩文件
大小 : 20 KB
HtmlReportForm
一个可自定义样式和脚本的页面形式的报告窗口
项目结构如下图:
web文件夹下三个文件是分别可以复制到生成目录的web文件夹下;
HtmlReportForm 是HTML报告窗体主要代码;
WebGenerater.cs 是生成页面代码,它优先读取生成目录web文件夹下的三个文件,读取失败则使用项目资源中的文件。
演示:
report.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>{0}</title> {1} </head> <body> {2} </body> </html>
report.css
/* common */ body, ul, ol, li { margin: 0; list-style: none; } img { border-width: 0; }
report.js
function zoomIn(){ var zoom = document.body.style.zoom ? parseFloat(document.body.style.zoom) : 1; if (zoom < 4.0) zoom = zoom + 0.1; document.body.style.zoom = zoom; } function zoomOut(){ var zoom = document.body.style.zoom ? parseFloat(document.body.style.zoom) : 1; if (zoom > 0.2) zoom = zoom - 0.1; document.body.style.zoom = zoom; }
WebGenerater.cs
using System; using System.IO; using HtmlReportDemo.Properties; namespace HtmlReportDemo { public static class WebGenerater { private const string WebFileDir = "web"; private const string WebFileHtml = "report.html"; private const string WebFileCss = "report.css"; private const string WebFileJs = "report.js"; private static string _html; private static string _css; private static string _js; public static string Generate() { string html = _html, css = _css, js = _js; if (string.IsNullOrEmpty(_html)) { LoadTemplates(out html, out css, out js); _html = html; _css = css; _js = js; } var title = "Demo"; var body = @"<a href=""http://blog.****.com/oyi319"" title=""访问博客"">BLOG!</a>"; css = string.Format("<mce:style><!-- {0} --></mce:style><style mce_bogus="1">{0}</style>", css); js = string.Format("<mce:script type="text/javascript"><!-- {0} // --></mce:script>", js); return string.Format(html, title, css + js, body); } private static void LoadTemplates(out string html, out string css, out string js) { html = ""; css = ""; js = ""; var path = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, WebFileDir); if (!Directory.Exists(path)) { try { Directory.CreateDirectory(path); } catch { Console.WriteLine(Resources.WebGenerater_LoadTemplates_Create_Directory__0__is_fault_, path); return; } } var htmlfile = Path.Combine(path, WebFileHtml); var cssfile = Path.Combine(path, WebFileCss); var jsfile = Path.Combine(path, WebFileJs); if (File.Exists(htmlfile)) { try { css = File.ReadAllText(htmlfile); } catch { Console.WriteLine(Resources.WebGenerater_LoadTemplates_Load_html_file__0__is_fault_,htmlfile); } } if (File.Exists(cssfile)) { try { css = File.ReadAllText(cssfile); } catch { Console.WriteLine(Resources.WebGenerater_LoadTemplates_Load_css_file__0__is_fault_, cssfile); } } if (File.Exists(jsfile)) { try { css = File.ReadAllText(jsfile); } catch { Console.WriteLine(Resources.WebGenerater_LoadTemplates_Load_js_file__0__is_fault_, jsfile); } } if (string.IsNullOrEmpty(html)) html = Resources.report_html; if (string.IsNullOrEmpty(css)) css = Resources.report_css; if (string.IsNullOrEmpty(js)) js = Resources.report_js; } } }
演示下载: