新系統環境下讀寫註冊表

       當前的主流系統以及不再是winXP系統,大部分都已經是win7,win8,而且都是64位的。之前一直用來讀寫註冊表的函數 GetProfileString WriteProfileString,現在已經不像之前用的那麼方便了,有些限制了。

       如果只是讀寫INI文件,當然是自定義路徑,直線使用原來的函數還是可以的。我也一直這麼用的,沒看到有什麼問題。但是今天遇到讀寫註冊表的事情時,發現不容易實現了。查閱資源,發現如下內容:


該函數有兩個同名原型,一個是windows API,一個是CWinApp的成員函數。
作爲API的情況,MSDN的說明如下:
The WriteProfileString function copies a string into the specified section of the Win.ini file. If Win.ini uses Unicode characters, the function writes Unicode characters to the file. Otherwise, the function writes ANSI characters.
Note This function is provided only for compatibility with 16-bit versions of Windows. Applications should store initialization information in the registry.
BOOL WriteProfileString(
LPCTSTR lpAppName,
LPCTSTR lpKeyName,
LPCTSTR lpString
);
總的來說,也就是,這個函數在32位機以後不再使用,存在的目的只是爲了與16位機兼容。
作爲CWinApp成員函數的情況:
MSDN說明:
Call this member function to write the specified string into the specified section of the application's registry or .INI file.
BOOL WriteProfileString(
LPCTSTR lpszSection,
LPCTSTR lpszEntry,
LPCTSTR lpszValue);
簡而言之,就是說這個函數寫的內容可能是在註冊表中,也可能是在.ini文件中,那麼究竟怎麼判斷呢?
先來看一個函數MSDN說明:
Causes application settings to be stored in the registry instead of INI files.
void SetRegistryKey(
LPCTSTR lpszRegistryKey
);
void SetRegistryKey(
UINT nIDRegistryKey
);
翻譯過來很明瞭,這個函數就是用來控制程序初始化信息時存儲位置的,是註冊表,或者.ini文件。
如果想存到註冊表中,就先調用一下這個函數就OK了,默認是存儲在.ini文件中的。那麼問題又來了,這個.ini文件存在什麼地方?又叫什麼名字呢?
調試跟蹤到CWinApp::WriteProfileString中間,發現了這個函數:return ::WritePrivateProfileString(lpszSection, lpszEntry, lpszValue,m_pszProfileName);
然後根據m_pszProfileName的名字RPT.ini(因爲我的應用程序名字爲RPT.exe)查找,最後在C:\WINDOWS下查找到了RPT.ini的文件,打開看下,結果不錯。


以上爲網絡轉載內容,說的很明白了。我是隻用了CWinApp::WriteProfileString,就可以成功實現。實現時調用AfxGetApp()->GetProfileString,就可以了,但是注意GetProfileString函數和API函數的參數有變化,讀取出來的值是返回值,第三個參數是默認值,查閱MSDN,即可明瞭。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章