SYSTEM权限启动应用程序时,无法访问HKEY_CURRENT_USER下的注册表,可以同修改HKEY_USERS下的注册表项来实现设置默认打印机。
HKEY_USERS根键中保存的是默认用户(.DEFAULT)、当前登录用户(如ws)与软件(Software)的信息
HKEY_CURRENT_USER根键中保存的信息(当前用户的子键信息)与HKEY_USERS\.Default分支中所保存的信息是相同的,
任何对HKEY_CURRENT_USER根键中的信息的修改都会导致对HKEY_USERS\.Default中子键信息的修改,反之也是如此。
1 //Reference from:http://topic.csdn.net/u/20111201/07/b5092cbe-bf0a-40a3-a0f4-b7e596fc00e6.html
2 BOOL CCommonFun::GetRegeditSetDefaultPrinter(const CString &sUserId, const CString &sDefaultPrinter)
3 {
4 const int MAX_LEG = 256 * sizeof(TCHAR);
5 HKEY hKey;
6 DWORD dwRegNum = MAX_LEG;
7 TCHAR regBufferName[MAX_LEG] = {0};
8 if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList"),NULL, KEY_READ, &hKey) == ERROR_SUCCESS )
9 {
10 if(RegQueryInfoKey(hKey, NULL, NULL, NULL, &dwRegNum, NULL, NULL, NULL, NULL, NULL, NULL, NULL) == ERROR_SUCCESS)
11 {
12 for(int i = 0; i < (int)dwRegNum; i++)
13 {
14 DWORD dwRegSize = MAX_LEG;
15 RegEnumKeyEx(hKey, i, regBufferName, &dwRegSize, NULL, NULL, NULL, NULL);
16 DWORD dwType;
17 HKEY hSubKey;
18 if(RegOpenKeyEx(hKey, regBufferName, NULL, KEY_READ, &hSubKey) == ERROR_SUCCESS)
19 {
20 TCHAR regBufferValue[MAX_LEG] = {0};
21 dwRegSize = MAX_LEG;
22 RegQueryValueEx(hSubKey, _T("ProfileImagePath"), 0, &dwType, (LPBYTE)regBufferValue, &dwRegSize);
23 CString displayName = regBufferValue;
24 displayName = displayName.Mid(displayName.ReverseFind('\\') + 1, displayName.GetLength());
25 if(displayName.CompareNoCase(sUserId) == 0)
26 {
27 CString sPrinterRegPath;
28 sPrinterRegPath.Format("%s%s", regBufferName,"\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Windows");
29
30 HKEY hUserKey;
31 if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_USERS, sPrinterRegPath, 0, KEY_READ|KEY_WRITE|KEY_SET_VALUE,
32 &hUserKey))
33 {
34 LOG("打开打印机注册表项%s失败", sPrinterRegPath);
35 return FALSE;
36 }
37
38 TCHAR regDefaultValue[MAX_LEG] = {0};
39 dwRegSize = MAX_LEG;
40 RegQueryValueEx(hUserKey, _T("Device"), 0, &dwType, (LPBYTE)regDefaultValue, &dwRegSize);
41 CString sPrinterInfo = regDefaultValue;
42 sPrinterInfo = sPrinterInfo.Mid(sPrinterInfo.Find(","), sPrinterInfo.GetLength());
43 CString sDefaultInfo;
44 sDefaultInfo.Format("%s%s", sDefaultPrinter, sPrinterInfo);
45
46 if(ERROR_SUCCESS != RegSetValueEx(hUserKey, TEXT("Device"), 0, REG_SZ, (LPBYTE)(LPCTSTR)sDefaultInfo, sDefaultInfo.GetLength()))
47 {
48 LOG("写入注册表%s键值%s失败", sPrinterRegPath, sDefaultInfo);
49 RegCloseKey(hUserKey);
50 return FALSE;
51 }
52 RegCloseKey(hUserKey);
53 }
54 }
55 else
56 {
57 return FALSE; //打开键失败
58 }
59 RegCloseKey(hSubKey);
60 }
61 }
62 }
63 else
64 {
65 return FALSE; //打开键失败
66 }
67 RegCloseKey(hKey);
68 return TRUE;
69 }
posted on 2012-10-18 14:22
王海光 阅读(907)
评论(0) 编辑 收藏 引用 所属分类:
MFC