我是WinApi的新手,我想在我的D:驱动器中打开文本文件,但是这段代码不起作用。当我运行这个应用程序时,我有一个错误:"Windows找不到文件‘lobalizarion\Sorting\sortdefaults.nls’“。在控制台中,我有一条消息:“文件没有找到”,但我的驱动器上有它。
在我的代码中,我使用代码片段from:How to get hWnd of window opened by ShellExecuteEx.. hProcess?获取已创建的HINSTANCE的HWND。
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include <vector>
std::wstring stringToLPCTSTR(const std::string& s)
{
int len;
int slength = (int)s.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
std::wstring r(buf);
delete[] buf;
return r;
}
struct ProcessWindowsInfo
{
DWORD ProcessID;
std::vector<HWND> Windows;
ProcessWindowsInfo(DWORD const AProcessID) : ProcessID(AProcessID) {}
};
BOOL __stdcall EnumProcessWindowsProc(HWND hwnd, LPARAM lParam)
{
ProcessWindowsInfo *Info = reinterpret_cast<ProcessWindowsInfo*>(lParam);
DWORD WindowProcessID;
GetWindowThreadProcessId(hwnd, &WindowProcessID);
if (WindowProcessID == Info->ProcessID)
Info->Windows.push_back(hwnd);
return true;
}
int main()
{
SHELLEXECUTEINFOW sei;
sei.cbSize = sizeof(SHELLEXECUTEINFO);
sei.fMask = SEE_MASK_NOCLOSEPROCESS;
sei.hwnd = NULL;
sei.lpVerb = stringToLPCTSTR("open").c_str();
sei.lpFile = stringToLPCTSTR("D:\\file.txt").c_str();
sei.lpParameters = NULL;
sei.lpDirectory = stringToLPCTSTR("D:\\").c_str();;
sei.nShow = SW_SHOWNORMAL;
sei.hInstApp = NULL;
auto retval = ShellExecuteEx(&sei);
if (retval == 0) //check errors
{
if ((int)sei.hInstApp == SE_ERR_FNF)
std::cerr << "File was not found\n";
else
std::cerr << "Unexpected error occured\n";
}
else
{
WaitForInputIdle(sei.hProcess, INFINITE);
ProcessWindowsInfo info(GetProcessId(sei.hProcess));
EnumWindows((WNDENUMPROC)EnumProcessWindowsProc, reinterpret_cast<LPARAM>(&info));
}
std::cin.get();
return 0;
}发布于 2017-10-26 15:26:21
由std::wstring返回的stringToLPCTSTR()是临时的,用于分配结构SHELLEXECUTEINFOW的LPCTSTR成员。这意味着对c_str()的相应调用返回的指针在调用ShellExecuteEx()时可能不再有效。您需要找到一种不同的解决方案,例如,为std::wstring使用局部变量,但只要您只使用字符串文本,您就可以这样做。
sei.lpVerb = L"open";
sei.lpFile = L"D:\\file.txt";
sei.lpDirectory = L"D:\\";https://stackoverflow.com/questions/46957879
复制相似问题