首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Winapi ShellExecuteEx不打开文件

Winapi ShellExecuteEx不打开文件
EN

Stack Overflow用户
提问于 2017-10-26 15:08:22
回答 1查看 395关注 0票数 0

我是WinApi的新手,我想在我的D:驱动器中打开文本文件,但是这段代码不起作用。当我运行这个应用程序时,我有一个错误:"Windows找不到文件‘lobalizarion\Sorting\sortdefaults.nls’“。在控制台中,我有一条消息:“文件没有找到”,但我的驱动器上有它。

在我的代码中,我使用代码片段from:How to get hWnd of window opened by ShellExecuteEx.. hProcess?获取已创建的HINSTANCE的HWND。

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-26 15:26:21

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

代码语言:javascript
复制
sei.lpVerb = L"open";
sei.lpFile = L"D:\\file.txt";
sei.lpDirectory = L"D:\\";
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46957879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档