本文實例講述了WinForm通過操作注冊表實現限制軟件使用次數的方法。分享給大家供大家參考,具體如下:
1.創(chuàng)建注冊表文件:
打開記事本,輸入一些內容:
1
2
3
|
REGEDIT4 [HKEY_CURRENT_USER /Software/MyRegDataApp ] "UseTime" = "10" |
保存為“RegData.reg”
2.創(chuàng)建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" ); //不存在,則創(chuàng)建子項 RegKey = RootKey.OpenSubKey ( "MyRegDataApp" , true ); RegKey.SetValue ( "UseTime" ,( object )9); //創(chuàng)建鍵值,存儲可使用次數 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 ( "繼續(xù)使用,請購買本軟件!" , "提示" ,MessageBoxButtons.OK ,MessageBoxIcon.Information )== DialogResult.OK ) { Application.Exit (); } } else { RegKey.SetValue ( "UseTime" ,( object )newtime); //更新鍵值,可使用次數減1 } } catch { RegKey.SetValue ( "UseTime" ,( object )10); //創(chuàng)建鍵值,存儲可使用次數 MessageBox.Show ( "您可以免費使用本軟件10次!" , "感謝您首次使用" ); return ; } |
希望本文所述對大家C#程序設計有所幫助。