Winapi ShellExecuteEx不会打开该文件

时间:2017-10-26 15:08:23

标签: c++ winapi

我是WinApi的新手,我想在我的D:驱动器中打开文本文件,但这段代码不起作用。当我运行应用程序时,出现错误:" Windows无法找到文件&lobalizarion \ Sorting \ sortdefaults.nls'" ..并且在控制台中我有消息:"找不到文件",但我在驱动器上有它。

在我的代码中,我使用了来自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;
}

1 个答案:

答案 0 :(得分:4)

std::wstring返回的stringToLPCTSTR()是临时用户,用于分配结构LPCTSTR的{​​{1}}成员。这意味着,在您调用SHELLEXECUTEINFOW时,对c_str()的相应调用返回的指针可能不再有效。您需要为此找到不同的解决方案,例如通过使用ShellExecuteEx()的局部变量,但只要你只使用字符串文字,你就可以做到

std::wstring