0

我正在尝试使用 Qt 和 C++ 获取 Windows 路径。下面的代码编译,但没有得到 Qt 中的 windows 文件夹路径。相同的代码适用于 Visual Studio 2010

      wchar_t path[MAX_PATH];
      SHGetFolderPath(NULL, CSIDL_WINDOWS, NULL, 0, path);

以下代码更改似乎有效:

     int const bufferSize = 512;        
     QScopedPointer<WCHAR> dirPath(new WCHAR[bufferSize]);
     ZeroMemory( dirPath.operator ->(), bufferSize);
     SHGetFolderPath(NULL, CSIDL_WINDOWS, NULL, 0, dirPath.operator ->());
4

6 回答 6

2

没有 Qt 函数可以执行此操作,但是您可以通过读取环境变量来实现您的要求WINDIR

QStringList env_list(QProcess::systemEnvironment());

int idx = env_list.indexOf(QRegExp("^WINDIR=.*", Qt::CaseInsensitive));
if (idx > -1)
{
    QStringList windir = env_list[idx].split('=');
    qDebug() << "Var : " << windir[0];
    qDebug() << "Path: " << windir[1];
}

输出:

Var :  "WINDIR"
Path:  "C:\WINDOWS"
于 2012-06-05T17:14:30.323 回答
1
QString windowsInstallPath;

#ifdef Q_WS_WIN
QDir d;
if (d.cd("%windir%"))
    windowsInstallPath = d.absolutePath();
#endif

if (!windowsInstallPath.isNull())
    qDebug() << windowsInstallPath;
else
    qDebug() << "Not compiled for Windows";

应该管用。

于 2012-06-06T08:04:06.243 回答
1

我认为获取 Windows 目录的另一种非常合理的方法是从传递给程序的环境中获取它:

QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
qDebug() << env.value("windir");

https://doc.qt.io/qt-5/qprocessenvironment.html

于 2020-04-19T01:00:17.487 回答
0

我认为没有特定的 Qt 函数可以做到这一点。

最接近的是QSysinfo,它告诉您 Windows 版本。然而 SHGetFolderPath() 应该在 Qt 中工作,就像任何其他 win API 调用一样。

ps 在 Windows vista-> 这被替换为SHGetKnownFolderPath

于 2012-06-05T17:14:01.180 回答
0

如果您的应用程序不支持终端服务,您可能会在 TS 环境下获得不同的目录。今天我自己发现了这一点,并不是说我曾经被 %windir% 或 %SystemRoot% 或使用过 ShGetKnownFolderPath 或 GetWindowsDirectory API。

我选择使用存在于 Windows 2000 及更高版本的 GetSystemWindowsDirectory。微软的功能页面在这里。

Raymond Chen 的进一步解释在这里。

最后,代码...

它是用 Delphi 6 编写的。对此感到抱歉 :) 这是我目前正在编写的代码,但是如果您的语言中有 GetWindowsDirectory 的代码,那么只需要一些复制 + 重命名,因为函数签名是相同的。注意:此代码是 ANSI(...Delphi 6 中的单字节字符)。

function GetSystemWindowsDirectoryA(lpBuffer: PAnsiChar; uSize: UINT): UINT; stdcall; external kernel32 name 'GetSystemWindowsDirectoryA';

function GetSystemWindowsDirectory: string;
var
  buf: array[0..MAX_PATH] of Char;
  resultLength: Cardinal;
begin
  resultLength := GetSystemWindowsDirectoryA(@buf, SizeOf(buf));
  if resultLength = 0 then
    RaiseLastOSError;
  SetLength(Result, resultLength);
  Move(buf, PChar(Result)^, resultLength);
end;
于 2021-07-01T12:43:20.863 回答
0

这是一个单行解决方案:

QString winPath = QString::fromUtf8(qgetenv("windir"));

这也可以用于任何环境变量。我不确定qgetenvQt4 中是否可用,但它在 Qt5 中。

于 2017-09-14T09:17:04.467 回答