簡體   English   中英

如何使用 Qt/C++ 獲取 Windows 路徑

[英]How to get Windows path using Qt/C++

我正在嘗試使用 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 ->());

沒有 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"
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";

應該管用。

我認為獲取 Windows 目錄的另一種非常合理的方法是從傳遞給程序的環境中獲取它:

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

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

我認為沒有特定的 Qt 函數可以做到這一點。

最近的是QSysinfo ,它會告訴您 Windows 版本。 但是 SHGetFolderPath() 應該在 Qt 中與任何其他 win API 調用一樣工作。

ps 在 Windows vista-> 這被替換為SHGetKnownFolderPath

這是一個單行解決方案:

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

這也可以用於任何環境變量。 我不確定qgetenv在 Qt4 中是否可用,但它在 Qt5 中。

如果您的應用程序不知道終端服務,您可能會在 TS 環境下獲得不同的目錄。 今天我自己發現了這一點,並不是說我曾經被 %windir% 或 %SystemRoot% 或使用 ShGetKnownFolderPath 或 GetWindowsDirectory API 所困擾。

我選擇使用存在於 Windows 2000 及更高版本的 GetSystemWindowsDirectory。 Microsoft 的功能頁面在這里。

Raymond Chen 的進一步解釋 是here。

最后,代碼...

它是用 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM