C#教程:将应用软件的使用次数写入注册表
将应用软件的使用次数写入注册表
在软件推广的时候,经常先让用户试用一定的次数,如果超过试用的次数,则不允许再试用本软件,这样的程序可以通过将软件的试用次数写入注册表来实现。下面的示例实现了如果用户使用本程序超过30次,则不再允许用户使用,并提示用户进行注册。运行结果如图1、图2、图3所示。
图1 试用主窗体
图2 使用次数提示窗体
图3 过期提示窗体
其设计原理是:首先判断在注册表指定的位置处是否建立了限制软件试用次数的数据项,如果该数据项存在,则使用Registry类的GetValue函数读取“使用次数”,然后用Registry类的SetValue函数设置“使用次数”为读取的“使用次数”加1;如果该数据项不存在,则使用Registry类的SetValue函数设置“使用次数”为1。代码如下:
private void button1_Click(object sender, EventArgs e)
{
try
{
Int32 tLong = (Int32)Registry.GetValue("HKEY_LOCAL_MACHINESOFTWAREmrsoft", "UserTimes", 0);
if (tLong < 30)
{
int Times = tLong + 1;
Registry.SetValue("HKEY_LOCAL_MACHINESOFTWAREmrsoft", "UserTimes", Times);
MessageBox.Show("这是您第" + Times + "次使用。");
}
else
{
MessageBox.Show("试用期已到请重新注册");
Application.Exit();//退出应用程序
}
}
catch
{
Registry.SetValue("HKEY_LOCAL_MACHINESOFTWAREmrsoft", "UserTimes",
First_Count, RegistryValueKind.DWord);
MessageBox.Show("感谢您第次使用本软件");
}
}
完整程序代码如下:
★ ★★★★FrmUserTime.cs窗体代码文件完整程序代码★★★★★
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
namespace _7_02
{
public partial class FrmUserTime : Form
{
public FrmUserTime()
{
InitializeComponent();
}
private void FrmUserTime_Load(object sender, EventArgs e)
{
}
private int First_Count = 1;
private void button1_Click(object sender, EventArgs e)
{
try
{
Int32 tLong = (Int32)Registry.GetValue("HKEY_LOCAL_MACHINESOFTWAREmrsoft", "UserTimes", 0);
if (tLong < 30)
{
int Times = tLong + 1;
Registry.SetValue("HKEY_LOCAL_MACHINESOFTWAREmrsoft", "UserTimes", Times);
MessageBox.Show("这是您第" + Times + "次使用。");
}
else
{
MessageBox.Show("试用期以到请重新注册");
Application.Exit();
}
}
catch
{
Registry.SetValue("HKEY_LOCAL_MACHINESOFTWAREmrsoft", "UserTimes", First_Count, RegistryValueKind.DWord);
MessageBox.Show("感谢您第1次使用本软件");
}
}
//Const REG_SZ = 1