MFC登錄檔操作詳解
前置知識:VC WIN-API MFC
我總結了一些MFC操作登錄檔,大致分3種方法:
1)WIN-API
這個是當然的了,MFC也是基於WIN-API的,所以我們直接在MFC裡面應用WIN-API的登錄檔操作函式來對操作登錄檔,是沒有一點問題的。WIN-API的登錄檔操作大家可以去參考這3篇文章。
Registry Functions(登錄檔操作API)C語言登錄檔操作例項
Win32_API登錄檔類的編制以及使用
這3篇文章基本上概括了WIN-API登錄檔操作的一些方法和例項,大家看過之後應該就可以很順利的利用API來順利的操作登錄檔了。
2)用MFC提供的 CRegKey
既然我們是用MFC框架來寫程式,那麼用MFC封裝好的一些類來操作登錄檔也就理所當然了。
CRegKey類的詳細介紹(方法、成員)大家可以點選下面連結檢視:
這裡我們要注意的是,當我們使用MFC提供的這個類的時候,我們要首先在你的標頭檔案(.h)或者是原始檔(.cpp)裡面包含atlbase.h,也就是新增上一句:#include <atlbase.h>
下面是我在 Z-IEMONITOR 裡面添加了#include <atlbase.h>的地方(.h),大家可以參考下:
我們這裡是建立了一個SetReg成員,然後通過SetReg.Open()和SetReg.SetValue()來開啟和設定相應的鍵值,最後我們呼叫SetReg.Close()來釋放控制代碼。這樣,我們就完美的運用CRegKey類來解決了登錄檔操作的問題。
3)用SetRegistryKey函式
說到這裡,我們首先就要講一下SetRegistryKey函式的作用,通過查詢MSDN,我們得到了下面的內容:
CWinApp::SetRegistryKey
Causes application settings to be stored in the registry instead of INI files.
void SetRegistryKey(
LPCTSTR lpszRegistryKey
);
void SetRegistryKey(
UINT nIDRegistryKey
);
Parameters
lpszRegistryKey
Pointer to a string containing the name of the key.
nIDRegistryKey
ID/index of a key in the registry.
Remarks
This function sets m_pszRegistryKey, which is then used by the GetProfileInt, GetProfileString, WriteProfileInt, and WriteProfileStringmember functions of CWinApp. If this function has been called, the list of most recently-used (MRU) files is also stored in the registry. The registry key is usually the name of a company. It is stored in a key of the following form: HKEY_CURRENT_USER/Software/<company name>/<application name>/<section name>/<value name>.
看 了上面的內容,我們知道SetRegistryKey函式的作用就是:將原本應該存放到.ini的程式配置資訊,存放到登錄檔裡面。當我們用SetRegistryKey註冊了相應的登錄檔鍵值之後,下面的幾個原本用於讀寫.ini檔案的函式就被對映到進行讀寫登錄檔了:
Retrieves binary data from an entry in the application's .INI file. |
Retrieves an integer from an entry in the application's .INI file. |
Retrieves a string from an entry in the application's .INI file. |
Writes binary data to an entry in the application's .INI file. |
Writes an integer to an entry in the application's .INI file. |
Writes a string to an entry in the application's .INI file. |
下面我們來用具體的程式碼例子來給大家講解:首先,我們用SetRegistryKey函式來設定一下注冊表項,大家可以看下圖:
大家可以看到,本例子是在InitInstance()事件中加入了SetRegistryKey(_T("ZIEMONITOR")),這個代表什麼意思呢?意思就是說,我們將會在HKEY_CURRENT_USER//software//項下面建立一個名為 ZIEMONITOR 的分支,說他是準備建立,是因為,如果我們不呼叫上面說過的6個函式的話,就不會建立。下面是呼叫相應的函式來讀寫登錄檔的程式碼:
這裡用WriteProfileString和WriteProfileInt來對登錄檔進行了寫入操作
這裡呢,是用GetProfileInt和GetProfileString對登錄檔進行了讀取操作這裡需要說明的就是,這些函式都屬於CWinApp類,所以如果你的程式不是CWinApp的派生類,你就要在前面加上theApp或者AfxGetApp() 。大家可以感覺到,這種方法來操作登錄檔有一定的侷限性,但是用來實現儲存設定到登錄檔的話,也是綽綽有餘的。