DataGridView二维表头实例

RowMergeView.cs文件内容:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Design;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Reflection;
using System.Runtime.InteropServices;

    /// <summary>
    /// DataGridView行合并.请对属性MergeColumnNames 赋值既可
    /// </summary>
    public partial class RowMergeView : DataGridView
    {
        #region 构造函数
        public RowMergeView()
        {
            InitializeComponent();

        }
        #endregion
        #region 重写的事件
        protected override void OnPaint(PaintEventArgs pe)
        {
            // TODO: 在此处添加自定义绘制代码

            // 调用基类 OnPaint
            base.OnPaint(pe);
        }

        protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
        {
            try
            {
                if (e.RowIndex > -1 && e.ColumnIndex > -1)
                {
                    DrawCell(e);
                }
                else
                {
                    //二维表头
                    if (e.RowIndex == -1)
                    {
                        if (SpanRows.ContainsKey(e.ColumnIndex)) //被合并的列
                        {
                            //画边框
                            Graphics g = e.Graphics;
                            e.Paint(e.CellBounds, DataGridViewPaintParts.Background | DataGridViewPaintParts.Border);

                            int left = e.CellBounds.Left, top = e.CellBounds.Top + 2,
                            right = e.CellBounds.Right, bottom = e.CellBounds.Bottom;

                            switch (SpanRows[e.ColumnIndex].Position)
                            {
                                case 1:
                                    left += 2;
                                    break;
                                case 2:
                                    break;
                                case 3:
                                    right -= 2;
                                    break;
                            }

                            //画上半部分底色
                            g.FillRectangle(new SolidBrush(this._mergecolumnheaderbackcolor), left, top,
                            right - left, (bottom - top) / 2);

                            //画中线
                            g.DrawLine(new Pen(this.GridColor), left, (top + bottom) / 2,
                            right, (top + bottom) / 2);

                            //写小标题
                            StringFormat sf = new StringFormat();
                            sf.Alignment = StringAlignment.Center;
                            sf.LineAlignment = StringAlignment.Center;

                            g.DrawString(e.Value + "", e.CellStyle.Font, Brushes.Black,
                            new Rectangle(left, (top + bottom) / 2, right - left, (bottom - top) / 2), sf);
                            left = this.GetColumnDisplayRectangle(SpanRows[e.ColumnIndex].Left, true).Left - 2;

                            if (left < 0) left = this.GetCellDisplayRectangle(-1, -1, true).Width;
                            right = this.GetColumnDisplayRectangle(SpanRows[e.ColumnIndex].Right, true).Right - 2;
                            if (right < 0) right = this.Width;

                            g.DrawString(SpanRows[e.ColumnIndex].Text, e.CellStyle.Font, Brushes.Black,
                            new Rectangle(left, top, right - left, (bottom - top) / 2), sf);
                            e.Handled = true;
                        }
                    }
                }
                base.OnCellPainting(e);
            }
            catch
            { }
        }
        protected override void OnCellClick(DataGridViewCellEventArgs e)
        {
            base.OnCellClick(e);
        }
        #endregion
        #region 自定义方法
        /// <summary>
        /// 画单元格
        /// </summary>
        /// <param name="e"></param>
        private void DrawCell(DataGridViewCellPaintingEventArgs e)
        {
            if (e.CellStyle.Alignment == DataGridViewContentAlignment.NotSet)
            {
                e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            }
            Brush gridBrush = new SolidBrush(this.GridColor);
            SolidBrush backBrush = new SolidBrush(e.CellStyle.BackColor);
            SolidBrush fontBrush = new SolidBrush(e.CellStyle.ForeColor);
            int cellwidth;
            //上面相同的行数
            int UpRows = 0;
            //下面相同的行数
            int DownRows = 0;
            //总行数
            int count = 0;
            if (this.MergeColumnNames.Contains(this.Columns[e.ColumnIndex].Name) && e.RowIndex != -1)
            {
                cellwidth = e.CellBounds.Width;
                Pen gridLinePen = new Pen(gridBrush);
                string curValue = e.Value == null ? "" : e.Value.ToString().Trim();
                string curSelected = this.CurrentRow.Cells[e.ColumnIndex].Value == null ? "" : this.CurrentRow.Cells[e.ColumnIndex].Value.ToString().Trim();
                if (!string.IsNullOrEmpty(curValue))
                {
                    #region 获取下面的行数
                    for (int i = e.RowIndex; i < this.Rows.Count; i++)
                    {
                        if (this.Rows[i].Cells[e.ColumnIndex].Value.ToString().Equals(curValue))
                        {
                            //this.Rows[i].Cells[e.ColumnIndex].Selected = this.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected;

                            DownRows++;
                            if (e.RowIndex != i)
                            {
                                cellwidth = cellwidth < this.Rows[i].Cells[e.ColumnIndex].Size.Width ? cellwidth : this.Rows[i].Cells[e.ColumnIndex].Size.Width;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                    #endregion
                    #region 获取上面的行数
                    for (int i = e.RowIndex; i >= 0; i--)
                    {
                        if (this.Rows[i].Cells[e.ColumnIndex].Value.ToString().Equals(curValue))
                        {
                            //this.Rows[i].Cells[e.ColumnIndex].Selected = this.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected;
                            UpRows++;
                            if (e.RowIndex != i)
                            {
                                cellwidth = cellwidth < this.Rows[i].Cells[e.ColumnIndex].Size.Width ? cellwidth : this.Rows[i].Cells[e.ColumnIndex].Size.Width;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                    #endregion
                    count = DownRows + UpRows - 1;
                    if (count < 2)
                    {
                        return;
                    }
                }
                if (this.Rows[e.RowIndex].Selected)
                {
                    backBrush.Color = e.CellStyle.SelectionBackColor;
                    fontBrush.Color = e.CellStyle.SelectionForeColor;
                }
                //以背景色填充
                e.Graphics.FillRectangle(backBrush, e.CellBounds);
                //画字符串
                PaintingFont(e, cellwidth, UpRows, DownRows, count);
                if (DownRows == 1)
                {
                    e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
                    count = 0;
                }
                // 画右边线
                e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);

                e.Handled = true;
            }
        }
        /// <summary>
        /// 画字符串
        /// </summary>
        /// <param name="e"></param>
        /// <param name="cellwidth"></param>
        /// <param name="UpRows"></param>
        /// <param name="DownRows"></param>
        /// <param name="count"></param>
        private void PaintingFont(System.Windows.Forms.DataGridViewCellPaintingEventArgs e, int cellwidth, int UpRows, int DownRows, int count)
        {
            SolidBrush fontBrush = new SolidBrush(e.CellStyle.ForeColor);
            int fontheight = (int)e.Graphics.MeasureString(e.Value.ToString(), e.CellStyle.Font).Height;
            int fontwidth = (int)e.Graphics.MeasureString(e.Value.ToString(), e.CellStyle.Font).Width;
            int cellheight = e.CellBounds.Height;

            if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomCenter)
            {
                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y + cellheight * DownRows - fontheight);
            }
            else if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomLeft)
            {
                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y + cellheight * DownRows - fontheight);
            }
            else if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomRight)
            {
                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y + cellheight * DownRows - fontheight);
            }
            else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleCenter)
            {
                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
            }
            else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleLeft)
            {
                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
            }
            else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleRight)
            {
                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
            }
            else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopCenter)
            {
                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1));
            }
            else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopLeft)
            {
                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y - cellheight * (UpRows - 1));
            }
            else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopRight)
            {
                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y - cellheight * (UpRows - 1));
            }
            else
            {
                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
            }
        }
        #endregion
        #region 属性
        /// <summary>
        /// 设置或获取合并列的集合
        /// </summary>
        [MergableProperty(false)]
        [Editor("System.Windows.Forms.Design.ListControlStringCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
        [DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Visible)]
        [Localizable(true)]
        [Description("设置或获取合并列的集合"), Browsable(true), Category("单元格合并")]
        public List<string> MergeColumnNames
        {
            get
            {
                return _mergecolumnname;
            }
            set
            {
                _mergecolumnname = value;
            }
        }
        private List<string> _mergecolumnname = new List<string>();
        #endregion
        #region 二维表头
        private struct SpanInfo //表头信息
        {
            public SpanInfo(string Text, int Position, int Left, int Right)
            {
                this.Text = Text;
                this.Position = Position;
                this.Left = Left;
                this.Right = Right;
            }

            public string Text; //列主标题
            public int Position; //位置,1:左,2中,3右
            public int Left; //对应左行
            public int Right; //对应右行
        }
        private Dictionary<int, SpanInfo> SpanRows = new Dictionary<int, SpanInfo>();//需要2维表头的列
        /// <summary>
        /// 合并列
        /// </summary>
        /// <param name="ColIndex">列的索引</param>
        /// <param name="ColCount">需要合并的列数</param>
        /// <param name="Text">合并列后的文本</param>
        public void AddSpanHeader(int ColIndex, int ColCount, string Text)
        {
            if (ColCount < 2)
            {
                throw new Exception("行宽应大于等于2,合并1列无意义。");
            }
            //将这些列加入列表
            int Right = ColIndex + ColCount - 1; //同一大标题下的最后一列的索引
            SpanRows[ColIndex] = new SpanInfo(Text, 1, ColIndex, Right); //添加标题下的最左列
            SpanRows[Right] = new SpanInfo(Text, 3, ColIndex, Right); //添加该标题下的最右列
            for (int i = ColIndex + 1; i < Right; i++) //中间的列
            {
                SpanRows[i] = new SpanInfo(Text, 2, ColIndex, Right);
            }
        }
        /// <summary>
        /// 清除合并的列
        /// </summary>
        public void ClearSpanInfo()
        {
            SpanRows.Clear();
            //ReDrawHead();
        }
        private void DataGridViewEx_Scroll(object sender, ScrollEventArgs e)
        {
            if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)// && e.Type == ScrollEventType.EndScroll)
            {
                timer1.Enabled = false; timer1.Enabled = true;
            }
        }
        //刷新显示表头
        public void ReDrawHead()
        {
            foreach (int si in SpanRows.Keys)
            {
                this.Invalidate(this.GetCellDisplayRectangle(si, -1, true));
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            ReDrawHead();
        }
        /// <summary>
        /// 二维表头的背景颜色
        /// </summary>
        [Description("二维表头的背景颜色"), Browsable(true), Category("二维表头")]
        public Color MergeColumnHeaderBackColor
        {
            get { return this._mergecolumnheaderbackcolor; }
            set { this._mergecolumnheaderbackcolor = value; }
        }
        private Color _mergecolumnheaderbackcolor = System.Drawing.SystemColors.Control;
        #endregion
    }
使用时调用:
    rowMergeView1.AddSpanHeader(7, 4, "表头标题")
    7为开始列,4为所跨列数。


分享按钮		

【转载】C#调用dll时的类型转换总结

C++(Win 32) C#
char** 作为输入参数转为char[],通过Encoding类对这个string[]进行编码后得到的一个char[]
作为输出参数转为byte[],通过Encoding类对这个byte[]进行解码,得到字符串
C++ Dll接口:

void CplusplusToCsharp(in char** AgentID, out char** AgentIP);

C#中的声明:

[DllImport("Example.dll")]

public static extern void CplusplusToCsharp(char[] AgentID, byte[] AgentIP);

C#中的调用:

Encoding encode = Encoding.Default;

byte[] tAgentID;

byte[] tAgentIP;

string[] AgentIP;

tAgentID = new byte[100];

tAgentIP = new byte[100];

CplusplusToCsharp(encode.GetChars(tAgentID), tAgentIP);

AgentIP[i] = encode.GetString(tAgentIP,i*Length,Length);

Handle IntPtr
Hwnd IntPtr
int* ref int
int& ref int
void* IntPtr
unsigned char* ref byte
BOOL bool
DWORD int 或 uint(int 更常用一些)
枚举类型 Win32:

BOOL MessageBeep(UINT uType // 声音类型); 其中的声音类型为枚举类型中的某一值。

C#:

用户需要自己定义一个枚举类型:

public enum BeepType

{

SimpleBeep = -1,

IconAsterisk = 0×00000040,

IconExclamation = 0×00000030,

IconHand = 0×00000010,

IconQuestion = 0×00000020,

Ok = 0×00000000,

}

C#中导入该函数:

[DllImport("user32.dll")]

public static extern bool MessageBeep(BeepType beepType);

C#中调用该函数:

MessageBeep(BeepType.IconQuestion);

结构类型 Win32:

使用结构指针作为参数的函数:

BOOL GetSystemPowerStatus(

LPSYSTEM_POWER_STATUS lpSystemPowerStatus

);

Win32中该结构体的定义:

typedef struct _SYSTEM_POWER_STATUS {

BYTE  ACLineStatus;

BYTE  BatteryFlag;

BYTE  BatteryLifePercent;

BYTE  Reserved1;

DWORD BatteryLifeTime;

DWORD BatteryFullLifeTime;

} SYSTEM_POWER_STATUS, *LPSYSTEM_POWER_STATUS;

C#:

用户自定义相应的结构体:

struct SystemPowerStatus

{

byte ACLineStatus;

byte batteryFlag;

byte batteryLifePercent;

byte reserved1;

int batteryLifeTime;

int batteryFullLifeTime;

}

C#中导入该函数:

[DllImport("kernel32.dll")]

public static extern bool GetSystemPowerStatus(

ref SystemPowerStatus systemPowerStatus);

C#中调用该函数:

SystemPowerStatus sps;

….sps初始化赋值……

GetSystemPowerStatus(ref sps);

字符串 对于字符串的处理分为以下几种情况:

1、  字符串常量指针的处理(LPCTSTR),也适应于字符串常量的处理,.net中的string类型是不可变的类型。

2、  字符串缓冲区的处理(char*),即对于变长字符串的处理,.net中StringBuilder可用作缓冲区

Win32:

BOOL GetFile(LPCTSTR lpRootPathName);

C#:

函数声明:

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]

static extern bool GetFile (

[MarshalAs(UnmanagedType.LPTStr)]

string rootPathName);

函数调用:

string pathname;

GetFile(pathname);

备注:

DllImport中的CharSet是为了说明自动地调用该函数相关的Ansi版本或者Unicode版本

 

变长字符串处理:

C#:

函数声明:

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]

public static extern int GetShortPathName(

[MarshalAs(UnmanagedType.LPTStr)]

string path,

[MarshalAs(UnmanagedType.LPTStr)]

StringBuilder shortPath,

int shortPathLength);

函数调用:

StringBuilder shortPath = new StringBuilder(80);

int result = GetShortPathName(

@”d:\test.jpg”, shortPath, shortPath.Capacity);

string s = shortPath.ToString();

struct 具有内嵌字符数组的结构:

Win32:

typedef struct _TIME_ZONE_INFORMATION {

LONG    Bias;

WCHAR   StandardName[ 32 ];

SYSTEMTIME StandardDate;

LONG    StandardBias;

WCHAR   DaylightName[ 32 ];

SYSTEMTIME DaylightDate;

LONG    DaylightBias;

} TIME_ZONE_INFORMATION, *PTIME_ZONE_INFORMATION;

C#:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]

struct TimeZoneInformation

{

public int bias;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]

public string standardName;

SystemTime standardDate;

public int standardBias;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]

public string daylightName;

SystemTime daylightDate;

public int daylightBias;

}

具有回调的函数 Win32:

BOOL EnumDesktops(

HWINSTA hwinsta,       // 窗口实例的句柄

DESKTOPENUMPROC lpEnumFunc, // 回调函数

LPARAM lParam        // 用于回调函数的值

);

回调函数DESKTOPENUMPROC的声明:

BOOL CALLBACK EnumDesktopProc(

LPTSTR lpszDesktop, // 桌面名称

LPARAM lParam    // 用户定义的值

);

C#:

将回调函数的声明转化为委托:

delegate bool EnumDesktopProc(

[MarshalAs(UnmanagedType.LPTStr)]

string desktopName,

int lParam);

该函数在C#中的声明:

[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern bool EnumDesktops(
IntPtr windowStation,
EnumDesktopProc callback,
int lParam);

该表对C#中调用win32函数,以及c++编写的dll时参数及返回值的转换做了一个小的总结,如果想进一步了解这方面内容的话,可以参照msdn中“互操作封送处理”一节。

转载于:http://blog.csdn.net/xiaochongchong1248/archive/2010/01/13/5181345.aspx

分享按钮

【转载】C# winform DataGridView 的18种常见属性

C# winform DataGridView 的18种常见属性

C# winform DataGridView 属性说明
① 取得或者修改当前单元格的内容
② 设定单元格只读
③ 不显示最下面的新行
④ 判断新增行
⑤ 行的用户删除操作的自定义
⑥ 行、列的隐藏和删除
⑦ 禁止列或者行的Resize
⑧ 列宽和行高以及列头的高度和行头的宽度的自动调整
⑨ 冻结列或行
⑩ 列顺序的调整
⑪ 行头列头的单元格
⑫ 剪切板的操作
⑬ 单元格的ToolTip的设置
⑭ 右键菜单(ContextMenuStrip)的设置
⑮ 单元格的边框、 网格线样式的设定
⑯ 单元格表示值的设定
⑰ 用户输入时,单元格输入值的设定
⑱ 设定新加行的默认值

——————————————————————————–
① DataGridView 取得或者修改当前单元格的内容:

当前单元格指的是 DataGridView 焦点所在的单元格,它可以通过 DataGridView 对象的 CurrentCell 属性取得。如果当前单元格不存在的时候,返回Nothing(C#是null)

// 取得当前单元格内容
Console.WriteLine(DataGridView1.CurrentCell.Value);
// 取得当前单元格的列 Index
Console.WriteLine(DataGridView1.CurrentCell.ColumnIndex);
// 取得当前单元格的行 Index
Console.WriteLine(DataGridView1.CurrentCell.RowIndex);

另外,使用 DataGridView.CurrentCellAddress 属性(而不是直接访问单元格)来确定单元格所在的
行: DataGridView.CurrentCellAddress.Y
列: DataGridView.CurrentCellAddress.X 。这对于避免取消共享行的共享非常有用。

当前的单元格可以通过设定 DataGridView 对象的 CurrentCell 来改变。可以通过 CurrentCell 来设定
DataGridView 的激活单元格。将 CurrentCell 设为 Nothing(null) 可以取消激活的单元格。
——————————————————————————–

// 设定 (0, 0) 为当前单元格
DataGridView1.CurrentCell = DataGridView1[0, 0];
在整行选中模式开启时,你也可以通过 CurrentCell 来设定选定行。
/// 向下遍历
private void button4_Click(object sender, EventArgs e)
…{
int row = this.dataGridView1.CurrentRow.Index + 1;
if (row > this.dataGridView1.RowCount – 1)
row = 0;
this.dataGridView1.CurrentCell = this.dataGridView1[0, row];
}
/// 向上遍历
private void button5_Click(object sender, EventArgs e)
…{
int row = this.dataGridView1.CurrentRow.Index – 1;
if (row < 0)
row = this.dataGridView1.RowCount – 1;
this.dataGridView1.CurrentCell = this.dataGridView1[0, row];
}
* 注意: this.dataGridView 的索引器的参数是: columnIndex, rowIndex 或是 columnName, rowIndex
这与习惯不同。

——————————————————————————–
② DataGridView 设定单元格只读:

1) 使用 ReadOnly 属性
如果希望,DataGridView 内所有单元格都不可编辑, 那么只要:

// 设置 DataGridView1 为只读
DataGridView1.ReadOnly = true;此时,用户的新增行操作和删除行操作也被屏蔽了。

如果希望,DataGridView 内某个单元格不可编辑, 那么只要:

// 设置 DataGridView1 的第2列整列单元格为只读
DataGridView1.Columns[1].ReadOnly = true;

// 设置 DataGridView1 的第3行整行单元格为只读
DataGridView1.Rows[2].ReadOnly = true;

// 设置 DataGridView1 的[0,0]单元格为只读
DataGridView1[0, 0].ReadOnly = true;

2) 使用 EditMode 属性
DataGridView.EditMode 属性被设置为 DataGridViewEditMode.EditProgrammatically 时,用户就不能手动编辑单元格的内容了。但是可以通过程序,调用 DataGridView.BeginEdit 方法,使单元格进入编辑模式进行编辑。

DataGridView1.EditMode = DataGridViewEditMode.EditProgrammatically;

3) 根据条件设定单元格的不可编辑状态
当一个一个的通过单元格坐标设定单元格 ReadOnly 属性的方法太麻烦的时候,你可以通过 CellBeginEdit 事件来取消单元格的编辑。

// CellBeginEdit 事件处理方法
private void DataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//是否可以进行编辑的条件检查
if (dgv.Columns[e.ColumnIndex].Name == “Column1″ && !(bool)dgv["Column2", e.RowIndex].Value)
{
// 取消编辑
e.Cancel = true;
}
}

——————————————————————————–
③ DataGridView 不显示最下面的新行:

通常 DataGridView 的最下面一行是用户新追加的行(行头显示 * )。如果不想让用户新追加行即不想显示该新行,可以将 DataGridView 对象的 AllowUserToAddRows 属性设置为 False。

// 设置用户不能手动给 DataGridView1 添加新行
DataGridView1.AllowUserToAddRows = false;
但是,可以通过程序: DataGridViewRowCollection.Add 为 DataGridView 追加新行。

补足: 如果 DataGridView 的 DataSource 绑定的是 DataView, 还可以通过设置 DataView.AllowAdd
属性为 False 来达到同样的效果。
——————————————————————————–
④ DataGridView 判断新增行:

DataGridView 的AllowUserToAddRows属性为True时也就是允许用户追加新行的场合下,DataGridView的最后一行就是新追加的行(*行)。
使用 DataGridViewRow.IsNewRow 属性可以判断哪一行是新追加的行。另外,通过DataGridView.NewRowIndex 可以获取新行的行序列号.
在没有新行的时候,NewRowIndex = -1。

——————————————————————————–
⑤ DataGridView 行的用户删除操作的自定义:

1) 无条件的限制行删除操作。
默认时,DataGridView 是允许用户进行行的删除操作的。如果设置 DataGridView对象的AllowUserToDeleteRows属性为 False 时, 用户的行删除操作就被禁止了。

// 禁止DataGridView1的行删除操作。
DataGridView1.AllowUserToDeleteRows = false;
但是,通过 DataGridViewRowCollection.Remove 还是可以进行行的删除。
补足: 如果 DataGridView 绑定的是 DataView 的话,通过 DataView.AllowDelete 也可以控制行的删除。

2) 行删除时的条件判断处理。
用户在删除行的时候,将会引发 DataGridView.UserDeletingRow 事件。 在这个事件里,可以判断条件并取消删除操作。

// DataGridView1 的 UserDeletingRow 事件
private void DataGridView1_UserDeletingRow( object sender, DataGridViewRowCancelEventArgs e)
{
// 删除前的用户确认。
if (MessageBox.Show(“确认要删除该行数据吗?”, “删除确认”,
MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
{
// 如果不是 OK,则取消。
e.Cancel = true;
}
}

——————————————————————————–
⑥ DataGridView 行、列的隐藏和删除:

1) 行、列的隐藏

// DataGridView1的第一列隐藏
DataGridView1.Columns[0].Visible = false;

// DataGridView1的第一行隐藏
DataGridView1.Rows[0].Visible = false;

2) 行头、列头的隐藏

// 列头隐藏
DataGridView1.ColumnHeadersVisible = false;

// 行头隐藏
DataGridView1.RowHeadersVisible = false;

3) 行和列的删除

‘ 删除名为”Column1″的列
DataGridView1.Columns.Remove(“Column1″);

‘ 删除第一列

DataGridView1.Columns.RemoveAt(0);
‘ 删除第一行
DataGridView1.Rows.RemoveAt(0);

4) 删除选中行

foreach (DataGridViewRow r in DataGridView1.SelectedRows)
{
if (!r.IsNewRow)
{
DataGridView1.Rows.Remove(r);
}
}

——————————————————————————–
⑦ DataGridView 禁止列或者行的Resize:

1) 禁止所有的列或者行的Resize

// 禁止用户改变DataGridView1的所有列的列宽
DataGridView1.AllowUserToResizeColumns = false;

//禁止用户改变DataGridView1の所有行的行高
DataGridView1.AllowUserToResizeRows = false;
但是可以通过 DataGridViewColumn.Width 或者 DataGridViewRow.Height 属性设定列宽和行高。

2) 禁止指定行或者列的Resize

// 禁止用户改变DataGridView1的第一列的列宽
DataGridView1.Columns[0].Resizable = DataGridViewTriState.False;

// 禁止用户改变DataGridView1的第一列的行宽
DataGridView1.Rows[0].Resizable = DataGridViewTriState.False;

关于 NoSet :
当 Resizable 属性设为 DataGridViewTriState.NotSet 时, 实际上会默认以 DataGridView 的 AllowUserToResizeColumns 和 AllowUserToResizeRows 的属性值进行设定。
比如: DataGridView.AllowUserToResizeColumns = False 且 Resizable 是 NoSet 设定时,Resizable = False 。

判断 Resizable 是否是继承设定了 DataGridView 的 AllowUserToResizeColumns 和 AllowUserToResizeRows 的属性值,
可以根据 State 属性判断。如果 State 属性含有 ResizableSet,那么说明没有继承设定。
3) 列宽和行高的最小值的设定

// 第一列的最小列宽设定为 100
DataGridView1.Columns[0].MinimumWidth = 100;

// 第一行的最小行高设定为 50
DataGridView1.Rows[0].MinimumHeight = 50;

4) 禁止用户改变行头的宽度以及列头的高度

// 禁止用户改变列头的高度
DataGridView1.ColumnHeadersHeightSizeMode =
DataGridViewColumnHeadersHeightSizeMode.DisableResizing;

// 设置用户改变行头的宽度
DataGridView1.RowHeadersWidthSizeMode =
DataGridViewRowHeadersWidthSizeMode.EnableResizing;
——————————————————————————–
⑧ DataGridView 列宽和行高自动调整的设定:

1) 设定行高和列宽自动调整

// 设定包括Header和所有单元格的列宽自动调整
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

// 设定包括Header和所有单元格的行高自动调整
DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
AutoSizeColumnsMode 属性的设定值枚举请参照 msdn 的 DataGridViewAutoSizeRowsMode 说明。

2)指定列或行自动调整

// 第一列自动调整
DataGridView1.Columns[0].AutoSizeMode =
DataGridViewAutoSizeColumnMode.DisplayedCells;
AutoSizeMode 设定为 NotSet 时, 默认继承的是 DataGridView.AutoSizeColumnsMode 属性。

3) 设定列头的高度和行头的宽度自动调整
// 设定列头的宽度可以自由调整
DataGridView1.ColumnHeadersHeightSizeMode =
DataGridViewColumnHeadersHeightSizeMode.AutoSize;

// 设定行头的宽度可以自由调整
DataGridView1.RowHeadersWidthSizeMode =
DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;

4) 随时自动调整
a, 临时的,让列宽自动调整,这和指定AutoSizeColumnsMode属性一样。
// 让 DataGridView1 的所有列宽自动调整一下。
DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

// 让 DataGridView1 的第一列的列宽自动调整一下。
DataGridView1.AutoResizeColumn(0, DataGridViewAutoSizeColumnMode.AllCells);上面调用的 AutoResizeColumns 和 AutoResizeColumn
当指定的是DataGridViewAutoSizeColumnMode.AllCells 的时候,参数可以省略。即:
DataGridView1.AutoResizeColumn(0) 和 DataGridView1.AutoResizeColumns()

b,临时的,让行高自动调整

// 让 DataGridView1 的所有行高自动调整一下。
DataGridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells);

//让 DataGridView1 的第一行的行高自动调整一下。
DataGridView1.AutoResizeRow(0, DataGridViewAutoSizeRowMode.AllCells);上面调用的 AutoResizeRows 和 AutoResizeRow
当指定的是DataGridViewAutoSizeRowMode.AllCells 的时候,参数可以省略。即:DataGridView1.AutoResizeRow (0) 和 DataGridView1.AutoResizeRows()

c,临时的,让行头和列头自动调整

// 列头高度自动调整
DataGridView1.AutoResizeColumnHeadersHeight();

// 行头宽度自动调整
DataGridView1.AutoResizeRowHeadersWidth(
DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
关于性能:
通过 AutoSizeColumnsMode 或者 AutoSizeRowsMode 属性所指定的单元格进行自动调整时,如果调整次数过于多那么将可能导致性能下降,
尤其是在行和列数比较多的情况下。在这时用 DisplayedCells 代替 AllCells 能减少非所见的单元格的调整,从而提高性能。
——————————————————————————–
⑨ DataGridView 冻结列或行

1) 列冻结
DataGridViewColumn.Frozen 属性为 True 时, 该列左侧的所有列被固定, 横向滚动时固定列不随滚动条滚动而左右移动。这对于重要列固定显示很有用。

// DataGridView1的左侧2列固定
DataGridView1.Columns[1].Frozen = true;
但是,DataGridView.AllowUserToOrderColumns = True 时,固定列不能移动到非固定列, 反之亦然。

2) 行冻结
DataGridViewRow.Frozen 属性为 True 时, 该行上面的所有行被固定, 纵向滚动时固定行不随滚动条滚动而上下移动。

// DataGridView1 的上3行固定
DataGridView1.Rows[2].Frozen = true;

——————————————————————————–
⑩ DataGridView 列顺序的调整

设定 DataGridView 的 AllowUserToOrderColumns 为 True 的时候, 用户可以自由调整列的顺序。
当用户改变列的顺序的时候,其本身的 Index 不会改变,但是 DisplayIndex 改变了。你也可以通过程序改变 DisplayIndex 来改变列的顺序。 列顺序发生改变时会引发 ColumnDisplayIndexChanged 事件:
// DataGridView1的ColumnDisplayIndexChanged事件处理方法
private void DataGridView1_ColumnDisplayIndexChanged(object sender,
DataGridViewColumnEventArgs e)
{
Console.WriteLine(“{0} 的位置改变到 {1} “,
e.Column.Name, e.Column.DisplayIndex);
}

 

 

—————-
⑪ 行头列头的单元格
[C#]
// 改变DataGridView1的第一列列头内容
DataGridView1.Columns[0].HeaderCell.Value = “第一列”; 

// 改变DataGridView1的第一行行头内容
DataGridView1.Rows[0].HeaderCell.Value = “第一行”;

// 改变DataGridView1的左上头部单元内容
DataGridView1.TopLeftHeaderCell.Value = “左上”;

另外你也可以通过 HeaderText 来改变他们的内容。
[C#]
// 改变DataGridView1的第一列列头内容
DataGridView1.Columns[0].HeaderText = “第一列”;

⑫ DataGridView 剪切板的操作
TOP
DataGridView.ClipboardCopyMode 属性被设定为 DataGridViewClipboardCopyMode.Disable 以外的情况时,「Ctrl + C」 按下的时候,被选择的单元格的内容会拷贝到系统剪切板内。格式有: Text, UnicodeText,Html, CommaSeparatedValue。可以直接粘贴到 Excel 内。

ClipboardCopyMode 还可以设定 Header部分是否拷贝: EnableAlwaysIncludeHeaderText 拷贝Header部分、EnableWithoutHeaderText 则不拷贝。默认是 EnableWithAutoHeaderText , Header 如果选择了的话,就拷贝。

1) 编程方式实现剪切板的拷贝

Clipboard.SetDataObject(DataGridView1.GetClipboardContent())

2) DataGridView 的数据粘贴

实现剪切板的拷贝比较容易,但是实现 DataGridView 的直接粘贴就比较难了。「Ctrl + V」按下进行粘贴时,DataGridView 没有提供方法,只能自己实现。

以下,是粘贴时简单的事例代码,将拷贝数据粘贴到以选择单元格开始的区域内。

[C#]
//当前单元格是否选择的判断
if (DataGridView1.CurrentCell == null)
return;
int insertRowIndex = DataGridView1.CurrentCell.RowIndex;

// 获取剪切板的内容,并按行分割
string pasteText = Clipboard.GetText();
if (string.IsNullOrEmpty(pasteText))
return;
pasteText = pasteText.Replace(” “, ” “);
pasteText = pasteText.Replace(‘ ‘, ‘ ‘);
pasteText.TrimEnd(new char[] { ‘ ‘ });
string[] lines = pasteText.Split(‘ ‘);

bool isHeader = true;
foreach (string line in lines)
{
// 是否是列头
if (isHeader)
{
isHeader = false;
continue;
}

// 按 Tab 分割数据
string[] vals = line.Split(‘ ‘);
// 判断列数是否统一
if (vals.Length – 1 != DataGridView1.ColumnCount)
throw new ApplicationException(“粘贴的列数不正确。”);
DataGridViewRow row = DataGridView1.Rows[insertRowIndex];
// 行头设定
row.HeaderCell.Value = vals[0];
// 单元格内容设定
for (int i = 0; i < row.Cells.Count; i++)
{
row.Cells[i].Value = vals[i + 1];
}

// DataGridView的行索引+1
insertRowIndex++;
}

________________________________________
⑬ DataGridView 单元格的ToolTip的设置

DataGridView.ShowCellToolTips = True 的情况下, 单元格的 ToolTip 可以表示出来。对于单元格窄小,无法完全显示的单元格, ToolTip 可以显示必要的信息。

1) 设定单元格的ToolTip内容
[C#]
// 设定单元格的ToolTip内容
DataGridView1[0, 0].ToolTipText = “该单元格的内容不能修改”;

// 设定列头的单元格的ToolTip内容
DataGridView1.Columns[0].ToolTipText = “该列只能输入数字”;

// 设定行头的单元格的ToolTip内容
DataGridView1.Rows[0].HeaderCell.ToolTipText = “该行单元格内容不能修改”;

2) CellToolTipTextNeeded 事件
在批量的单元格的 ToolTip 设定的时候,一个一个指定那么设定的效率比较低, 这时候可以利用 CellToolTipTextNeeded 事件。当单元格的 ToolTipText 变化的时候也会引发该事件。但是,当DataGridView的DataSource被指定且VirualMode=True的时候,该事件不会被引发。
[C#]
// CellToolTipTextNeeded事件处理方法
private void DataGridView1_CellToolTipTextNeeded(object sender,
DataGridViewCellToolTipTextNeededEventArgs e)
{
e.ToolTipText = e.ColumnIndex.ToString() + “, ” + e.RowIndex.ToString();
}

________________________________________
⑭ DataGridView 的右键菜单(ContextMenuStrip)

DataGridView, DataGridViewColumn, DataGridViewRow, DataGridViewCell 有 ContextMenuStrip 属性。可以通过设定 ContextMenuStrip 对象来控制 DataGridView 的右键菜单的显示。 DataGridViewColumn 的 ContextMenuStrip 属性设定了 除了列头以外的单元格的右键菜单。 DataGridViewRow 的 ContextMenuStrip 属性设定了除了行头以外的单元格的右键菜单。DataGridViewCell 的 ContextMenuStrip 属性设定了指定单元格的右键菜单。
[C#]
// DataGridView 的 ContextMenuStrip 设定
DataGridView1.ContextMenuStrip = this.ContextMenuStrip1;

// 列的 ContextMenuStrip 设定
DataGridView1.Columns[0].ContextMenuStrip = this.ContextMenuStrip2;
// 列头的 ContextMenuStrip 设定
DataGridView1.Columns[0].HeaderCell.ContextMenuStrip = this.ContextMenuStrip2;

// 行的 ContextMenuStrip 设定
DataGridView1.Rows[0].ContextMenuStrip = this.ContextMenuStrip3;

// 单元格的 ContextMenuStrip 设定
DataGridView1[0, 0].ContextMenuStrip = this.ContextMenuStrip4;
对于单元格上的右键菜单的设定,优先顺序是: Cell > Row > Column > DataGridView
⇒ CellContextMenuStripNeeded、RowContextMenuStripNeeded 事件
利用 CellContextMenuStripNeeded 事件可以设定单元格的右键菜单,尤其但需要右键菜单根据单元格值的变化而变化的时候。比起使用循环遍历,使用该事件来设定右键菜单的效率更高。但是,在DataGridView使用了DataSource绑定而且是VirtualMode的时候,该事件将不被引发。
[C#]
// CellContextMenuStripNeeded事件处理方法
private void DataGridView1_CellContextMenuStripNeeded(object sender,
DataGridViewCellContextMenuStripNeededEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (e.RowIndex < 0)
{
// 列头的ContextMenuStrip设定
e.ContextMenuStrip = this.ContextMenuStrip1;
}
else if (e.ColumnIndex < 0)
{
// 行头的ContextMenuStrip设定
e.ContextMenuStrip = this.ContextMenuStrip2;
}
else if (dgv[e.ColumnIndex, e.RowIndex].Value is int)
{
// 如果单元格值是整数时
e.ContextMenuStrip = this.ContextMenuStrip3;
}
}
同样,可以通过 RowContextMenuStripNeeded 事件来设定行的右键菜单。
[C#]
// RowContextMenuStripNeeded事件处理方法
private void DataGridView1_RowContextMenuStripNeeded(object sender,
DataGridViewRowContextMenuStripNeededEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
// 当”Column1″列是Bool型且为True时、设定其的ContextMenuStrip
object boolVal = dgv["Column1", e.RowIndex].Value;
Console.WriteLine(boolVal);
if (boolVal is bool && (bool)boolVal)
{
e.ContextMenuStrip = this.ContextMenuStrip1;
}
}

CellContextMenuStripNeeded 事件处理方法的参数中、「e.ColumnIndex=-1」表示行头、「e.RowIndex=-1」表示列头。RowContextMenuStripNeeded则不存在「e.RowIndex=-1」的情况。
________________________________________
⑮ DataGridView 的单元格的边框、 网格线样式的设定

1) DataGridView 的边框线样式的设定
DataGridView 的边框线的样式是通过 DataGridView.BorderStyle 属性来设定的。 BorderStyle 属性设定值是一个
BorderStyle 枚举: FixedSingle(单线,默认)、Fixed3D、None。

2) 单元格的边框线样式的设定
单元格的边框线的样式是通过 DataGridView.CellBorderStyle 属性来设定的。 CellBorderStyle 属性设定值是
DataGridViewCellBorderStyle 枚举。(详细参见 MSDN)
另外,通过 DataGridView.ColumnHeadersBorderStyle 和 RowHeadersBorderStyle 属性可以修改 DataGridView 的头部的单元格边框线样式。 属性设定值是 DataGridViewHeaderBorderStyle 枚举。(详细参见 MSDN)

3) 单元格的边框颜色的设定
单元格的边框线的颜色可以通过 DataGridView.GridColor 属性来设定的。默认是 ControlDarkDark 。但是只有在 CellBorderStyle 被设定为 Single、SingleHorizontal、SingleVertical 的条件下才能改变其边框线的颜色。同样,ColumnHeadersBorderStyle 以及 RowHeadersBorderStyle 只有在被设定为 Single 时,才能改变颜色。

4) 单元格的上下左右的边框线式样的单独设定
CellBorderStyle只能设定单元格全部边框线的式样。要单独改变单元格某一边边框式样的话,需要用到DataGridView.AdvancedCellBorderStyle属性。如示例:
[VB.NET]
‘ 单元格的上边和左边线设为二重线
‘ 单元格的下边和右边线设为单重线
DataGridView1.AdvancedCellBorderStyle.Top = _
DataGridViewAdvancedCellBorderStyle.InsetDouble
DataGridView1.AdvancedCellBorderStyle.Right = _
DataGridViewAdvancedCellBorderStyle.Inset
DataGridView1.AdvancedCellBorderStyle.Bottom = _
DataGridViewAdvancedCellBorderStyle.Inset
DataGridView1.AdvancedCellBorderStyle.Left = _
DataGridViewAdvancedCellBorderStyle.InsetDouble

同样,设定行头单元格的属性是: AdvancedRowHeadersBorderStyle, 设定列头单元格属性是:AdvancedColumnHeadersBorderStyle。
________________________________________
⑯ DataGridView 单元格表示值的自定义

通过CellFormatting事件,可以自定义单元格的表示值。(比如:值为Error的时候,单元格被设定为红色)
下面的示例:将“Colmn1”列的值改为大写。
[C#]
//CellFormatting 事件处理方法
private void DataGridView1_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
DataGridView dgv = (DataGridView)sender;

// 如果单元格是“Column1”列的单元格
if (dgv.Columns[e.ColumnIndex].Name == “Column1″ && e.Value is string)
{
// 将单元格值改为大写
string str = e.Value.ToString();
e.Value = str.ToUpper();
// 应用该Format,Format完毕。
e.FormattingApplied = true;
}
}

CellFormatting事件的DataGridViewCellFormattingEventArgs对象的Value属性一开始保存着未被格式化的值。当Value属性被设定表示用的文本之后,把FormattingApplied属性做为True,告知DataGridView文本已经格式化完毕。如果不这样做的话,DataGridView会根据已经设定的Format,NullValue,DataSourceNullValue,FormatProvider属性会将Value属性会被重新格式化一遍。
________________________________________
⑰ DataGridView 用户输入时,单元格输入值的设定

通过 DataGridView.CellParsing 事件可以设定用户输入的值。下面的示例:当输入英文文本内容的时候,立即被改变为大写。
[C#]
//CellParsing 事件处理方法
private void DataGridView1_CellParsing(object sender,
DataGridViewCellParsingEventArgs e)
{
DataGridView dgv = (DataGridView)sender;

//单元格列为“Column1”时
if (dgv.Columns[e.ColumnIndex].Name == “Column1″ &&
e.DesiredType == typeof(string))
{
//将单元格值设为大写
e.Value = e.Value.ToString().ToUpper();
//解析完毕
e.ParsingApplied = true;
}
}

________________________________________
⑱ DataGridView 新加行的默认值的设定

需要指定新加行的默认值的时候,可以在DataGridView.DefaultValuesNeeded事件里处理。在该事件中处理除了可以设定默认值以外,还可以指定某些特定的单元格的ReadOnly属性等。
[C#]
// DefaultValuesNeeded 事件处理方法
private void DataGridView1_DefaultValuesNeeded(object sender,
DataGridViewRowEventArgs e)
{
// 设定单元格的默认值
e.Row.Cells["Column1"].Value = 0;
e.Row.Cells["Column2"].Value = “-”;
}

原文地址:http://hi.baidu.com/iamheyjudy/blog/item/408e851b02e14b0d8718bf06.html

分享按钮

winform C#水晶报表打印预览

今天帮客户修改程序,需要用到水晶报表.

马上把之前做的关于水晶报表的项目拿出来看下.

看了好几个,但是都是直接打印.没用到水晶报表的打印预览功能.

立马在百度搜索了下.

找到一个

假设该预览用新窗体名称为ReportView,crystalreportview类型控件名为 CryView 主窗体名称为MainForm,打印按钮名称为 btn_Print 水晶报表名称为 CryReport.rpt 则点击打印按钮后,调用ReportView窗体,代码如下 ReportView myRp= newReportView(ReportSqlStr); myRp.ShowDialog(); 上面的代入参数ReportSqlStr是你检索数据所用的sql语句 在ReportView的load事件里写上 ds = myConn.GetData(“tmpTable”, tmpSql); CryReport myrpt = new CryReport(); myrpt.SetDataSource(ds); CryView.ReportSource = myrpt; CryView.RefreshReport();

还不懒.

 

分享按钮

【转载】C#软件注册

开发软件时,当用到商业用途时,注册码与激活码就显得很重要了。现在的软件破解技术实在在强了,各种国内外大型软件都有注册机制,但同时也不断地被破解。下面发的只是一个常用版本,发出源码被破就更容易了,但我们学习的是技术。当然也为以后自己的软件不会被轻易破解。
第一步。根据卷标,CPU序列号,生成机器码

?View Code CSHARP
// 取得设备硬盘的卷标号
public static string GetDiskVolumeSerialNumber()
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"d:\"");
disk.Get();
return disk.GetPropertyValue("VolumeSerialNumber").ToString();
}
//获得CPU的序列号
public static string getCpu()
{
string strCpu = null;
ManagementClass myCpu = new ManagementClass("win32_Processor");
ManagementObjectCollection myCpuConnection = myCpu.GetInstances();
foreach (ManagementObject myObject in myCpuConnection)
{
strCpu = myObject.Properties["Processorid"].Value.ToString();
break;
}
return strCpu;
}
//生成机器码
public static string getMNum()
{
string strNum = getCpu() + GetDiskVolumeSerialNumber();//获得24位Cpu和硬盘序列号
string strMNum = strNum.Substring(0, 24);//从生成的字符串中取出前24个字符做为机器码
return strMNum;
}
public static int[] intCode = new int[127];//存储密钥
public static int[] intNumber = new int[25];//存机器码的Ascii值
public static char[] Charcode = new char[25];//存储机器码字
public static void setIntCode()//给数组赋值小于10的数
{
for (int i = 1; i &lt; intCode.Length; i++)
{
intCode[i] = i % 9;
}
}

第二步。根据机器码 生成注册码

?View Code CSHARP
//生成注册码
public static string getRNum()
{
setIntCode();//初始化127位数组
for (int i = 1; i &lt; Charcode.Length; i++)//把机器码存入数组中
{
Charcode[i] = Convert.ToChar(getMNum().Substring(i - 1, 1));
}
for (int j = 1; j &lt; intNumber.Length; j++)//把字符的ASCII值存入一个整数组中。
{
intNumber[j] = intCode[Convert.ToInt32(Charcode[j])] + Convert.ToInt32(Charcode[j]);
}
string strAsciiName = "";//用于存储注册码
for (int j = 1; j &lt; intNumber.Length; j++)
{
if (intNumber[j] &gt;= 48 &amp;&amp; intNumber[j] &lt;= 57)//判断字符ASCII值是否0-9之间
{
strAsciiName += Convert.ToChar(intNumber[j]).ToString();
}
else if (intNumber[j] &gt;= 65 &amp;&amp; intNumber[j] &lt;= 90)//判断字符ASCII值是否A-Z之间
{
strAsciiName += Convert.ToChar(intNumber[j]).ToString();
}
else if (intNumber[j] &gt;= 97 &amp;&amp; intNumber[j] &lt;= 122)//判断字符ASCII值是否a-z之间
{
strAsciiName += Convert.ToChar(intNumber[j]).ToString();
}
else//判断字符ASCII值不在以上范围内
{
if (intNumber[j] &gt; 122)//判断字符ASCII值是否大于z
{
strAsciiName += Convert.ToChar(intNumber[j] - 10).ToString();
}
else
{
strAsciiName += Convert.ToChar(intNumber[j] - 9).ToString();
}
}
}
return strAsciiName;
}

第三步。检查注册状况,若没有注册,可自定义试用

?View Code CSHARP
///
/// 检查注册
///
 
private void CheckRegist()
{
this.btn_reg.Enabled = true;
RegistryKey retkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("software", true).CreateSubKey("wxk").CreateSubKey("wxk.INI");
foreach (string strRNum in retkey.GetSubKeyNames())//判断是否注册
{
if (strRNum == clsTools.getRNum())
{
thControl(true);
return;
}
}
thControl(false);
Thread th2 = new Thread(new ThreadStart(thCheckRegist2));
th2.Start();
}
}
///
/// 验证试用次数
/// 
 
private static void thCheckRegist2()
{
MessageBox.Show("您现在使用的是试用版,该软件可以免费试用3000000次!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
Int32 tLong;
try
{
tLong = (Int32)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\angel", "UseTimes", 0);
MessageBox.Show("感谢您已使用了" + tLong + "次", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\angel", "UseTimes", 0, RegistryValueKind.DWord);
MessageBox.Show("欢迎新用户使用本软件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
tLong = (Int32)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\angel", "UseTimes", 0);
if (tLong &lt; 3000000)
{
int Times = tLong + 1;
Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\angel", "UseTimes", Times);
}
else
{
MessageBox.Show("试用次数已到", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
Application.Exit();
}
}

本文转载于:博客园

原文地址:http://www.cnblogs.com/sijin/articles/1638802.html#1928326

分享按钮