1. 程式人生 > >WinForm通過操作登錄檔實現限制軟體使用次數的方法

WinForm通過操作登錄檔實現限制軟體使用次數的方法

1.建立登錄檔檔案:

開啟記事本,輸入一些內容:

?
1 2 3 REGEDIT4 [HKEY_CURRENT_USER /Software/MyRegDataApp ] "UseTime" =
"10"

儲存為“RegData.reg”

2.建立winform專案

引用名稱空間

?
1 using Microsoft.Win32 ;

在Form中啟用load事件,並新增程式碼

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 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 ; }