如何检查用户是否已打开应用程序

时间:2019-07-16 21:26:47

标签: c++ windows winapi

我创建了此代码,该代码允许用户打开文件,例如notepad ++,excel等。我想检查他是否打开了一个存在的文件。如果不是,仅给出错误消息。如果是文件,则打印“行得通”或类似的内容。

您给我的答案是完全无关的,这是关于其他功能不同的东西,太笼统了。

我试图检查该文件是否正确,但是不起作用。

    if (qorn == "notreal" || qorn == "4") {

            if (fileopen("ex") == true) { // all ways true ex is not a real file
                cout << "The file is good";
            }
            else {
                cout << "you don't have this file";
            }
        }

    bool fileopen(string url) {
    bool f = false;
    // .exe etc
    // what to do with the file - open is default
    // what is the name of the file you want to do something with
     ShellExecuteA(NULL,NULL/*null- open it as a deffualt*/, url.c_str(), NULL, NULL, SW_SHOWNORMAL);
     if (ShellExecuteA(NULL, NULL, url.c_str(), NULL, NULL, SW_SHOWNORMAL)) {
         f = true;
     }
     return f;
}



> You adviced me to this this as well which returns 000002 at the end if
> i print it

HINSTANCE fileopen(string url) {
    HINSTANCE num = 0;
    // .exe etc
    // what to do with the file - open is deffualt
    // what is the name of the file you want to do wsomething with
     num =ShellExecuteA(NULL,NULL/*null- open it as a deffualt*/, url.c_str(), NULL, NULL, SW_SHOWNORMAL);
     return num;

}

1 个答案:

答案 0 :(得分:0)

如文档所述,将返回值与32进行比较,否则显示错误消息。

(而且您仅标记了C ++,但是当您使用 ShellExecute

时,它也是Windows / Winapi

就像这样(在Windows上始终为Unicode)=>

(如果将Excel替换为不存在的文件,它将返回2(未找到文件))

                int hInst = (int)ShellExecute(NULL, NULL, L"Excel", NULL, NULL, SW_SHOWNORMAL);
                if (hInst <= 32)
                {
                    LPVOID lpMsgBuf = NULL;
                    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, hInst /* = GetLastError() */, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&lpMsgBuf, 0, NULL);
                    if (lpMsgBuf != NULL)
                    {
                        MessageBox(NULL, (LPCTSTR)lpMsgBuf, L"ShellExecute Error", MB_OK | MB_ICONSTOP);
                        LocalFree(lpMsgBuf);
                    }
                }