Dzwebs.Net

撰写电脑技术杂文十余年

C#利用注册表限制软件使用次数的代码

Admin | 2014-2-18 9:40:47 | 被阅次数 | 5860

温馨提示!

如果未能解决您的问题,请点击搜索;登陆可复制文章,点击登陆

  通过如下的代码,我们可以实现使用C#制作的软件,能通过注册表来限制软件使用次数的目的。

  请仔细,如下的代码为CS结构的软件,非BS结构的。

  第一步:先添加引用

  using System;
  using System.Drawing;
  using System.Collections;
  using System.ComponentModel;
  using System.Windows.Forms;
  using System.Data;
  using Microsoft.Win32 ;

  上面的引用中,注意最后一行,很关键。

  第二步:加如下代码到相应的事件中

  private void InitializeComponent()
  {
   //
   // Form1
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
   this.ClientSize = new System.Drawing.Size(292, 273);
   this.Name = "Form1";
   this.Text = "RegDataApp";
   this.Load += new System.EventHandler(this.Form1_Load);

   }

  第三:将代码放入Form1_Load事件中

  RegistryKey RootKey,RegKey; 

   //项名为:HKEY_CURRENT_USER\Software
   RootKey = Registry.CurrentUser.OpenSubKey ("Software",true);
   
   //打开子项:HKEY_CURRENT_USER\Software\MyRegDataApp
   if ((RegKey = RootKey.OpenSubKey ("MyRegDataApp",true)) == null)
   {
    RootKey.CreateSubKey("MyRegDataApp");//不存在,则创建子项
    RegKey = RootKey.OpenSubKey ("MyRegDataApp",true);
    RegKey.SetValue ("UseTime",(object)9); //创建键值,存储可使用次数
    MessageBox.Show ("您可以免费使用本软件10次!","感谢您首次使用");
    return;
   }

   try
   {
    object usetime = RegKey.GetValue ("UseTime");//读取键值,可使用次数
    MessageBox.Show ("你还可以使用本软件 :"+ usetime.ToString ()+ "次!","确认",MessageBoxButtons.OK ,MessageBoxIcon.Information );
    int newtime = Int32.Parse (usetime.ToString()) -1;

    if (newtime<0)
    {
     if (MessageBox.Show ("继续使用,请购买本软件!","提示",MessageBoxButtons.OK ,MessageBoxIcon.Information )== DialogResult.OK )
     {
      Application.Exit ();
     }
    }
    else
    {
     RegKey.SetValue ("UseTime",(object)newtime);//更新键值,可使用次数减1
    }
   }
   catch
   {
    RegKey.SetValue ("UseTime",(object)10); //创建键值,存储可使用次数
    MessageBox.Show ("您可以免费使用本软件10次!","感谢您首次使用");
    return;
   }


该杂文来自: 网站开发杂文

上一篇:FTP协议的PORT和PASV两种方式

下一篇:c#读写ini文件的知识介绍

网站备案号:

网站备案号:滇ICP备11001339号-7

版权属性:

Copyright 2007-2021-forever Inc. all Rights Reserved.

联系方式:

Email:dzwebs@126.com QQ:83539231 访问统计