我试图打开注册表并对其进行修改。这是我打开注册表的方式:
HKEY hKey;
LPCTSTR subKey = TEXT("a registry subkey to be opened");
RegOpenKeyEx(HKEY_LOCAL_MACHINE, subKey, 0, KEY_ALL_ACCESS , &hKey);
但这是一个问题,我想使用QString
实用地更改子项。然后像这样放置QString
:
QString subKeyString = QString("%1").arg(subKeyName);
LPCTSTR subKey = TEXT(subKeyString); //but it's not working here
我以为是因为我没有将QString
更改为LPCTSTR
,所以尝试了此解决方案,但仍然找不到解决方法,可以将自定义QString
放入TEXT
宏。我不太确定WinApi到底是什么,我只是尝试了我可能做的事情。
是否可以解决此问题?
编辑:
这是我将QString
转换为LPCTSTR
的方式:
QString testString = "converting QString to LPCSTR";
QByteArray testStringArr = testString.toLocal8Bit();
LPCSTR lp = LPCSTR(testStringArr.constData()); //the QString is converted to LPCTSTR
//but when I put the LPCSTR to the TEXT macro, the error is still there, like the next line below will not complie
LPCSTR lp = TEXT(LPCSTR(testStringArr.constData())); //This line will not work
答案 0 :(得分:6)
TEXT()
宏仅适用于编译时文字,不适用于运行时数据。 TCHAR
和相关的API旨在通过在char
和wchar_t
之间映射文字和映射函数来帮助人们将代码从基于ANSI的Win9x / ME迁移到基于Unicode的WinNT 4+。 A
和W
变体之间的名称。但是那些日子已经一去不复返了。
在这种情况下,正确解决方案是完全忽略TCHAR
,而只关注Unicode。 QString
是Unicode字符串的包装器。因此,仅使用基于Unicode的Registry API函数,并假装TCHAR
不存在。
在Windows上,基于Unicode的API需要UTF-16编码的wchar_t
字符串。使用QString::toStdWString()
方法获取std::wstring
,它是wchar_t
字符串的C ++包装器:
QString subKeyString = QString("%1").arg(subKeyName);
std::wstring subKey = subKeyString.toStdWString();
HKEY hKey;
RegOpenKeyExW(HKEY_LOCAL_MACHINE, subKey.c_str(), 0, KEY_ALL_ACCESS, &hKey);
或者,您可以使用QString::utf16()
方法。但是,它返回一个const ushort*
指针,因此您必须将其类型转换为const wchar_t*
:
QString subKeyString = QString("%1").arg(subKeyName);
LPCWSTR subKey = reinterpret_cast<LPCWSTR>(subKeyString.utf16());
HKEY hKey;
RegOpenKeyExW(HKEY_LOCAL_MACHINE, subKey, 0, KEY_ALL_ACCESS, &hKey);
答案 1 :(得分:4)
TEXT
宏应该有助于维护应用程序的非Unicode和Unicode版本。根据是否定义了_UNICODE
(或UNICODE
,已经不记得了)。 TEXT("foo")
将扩展为L"foo"
或仅扩展为"foo"
。同样,CreateWindow
将是采用CreateWindowW
参数的WCHAR*
或采用CreateWindowA
参数的CHAR*
。
考虑到现在是2018年,建议您不要使用该应用程序的TEXT
宏和非Unicode版本。 QString::utf16()
将返回WinAPI期望的UTF16字符串。如果使用“ Native wchar_t”编译器设置进行编译,则需要将utf16()
返回的内容强制转换为WCHAR*
。如果“本机wchar_t`已关闭,它将照常工作。
答案 2 :(得分:2)
I'm a bit late to the party perhaps, but to build on the other two answers, something as simple as this would oil the wheels:
inline const WCHAR *QStoWCHAR (const QString& qs)
{
return (const WCHAR *) qs.utf16 ();
}
And then you can do (for example):
RegOpenKeyExW (HKEY_LOCAL_MACHINE, QStoWCHAR (my_qstring), 0, KEY_ALL_ACCESS, &hKey);