use*_*578 6 c++ winapi c++-winrt
我有一个 Win32 程序,我想在其中添加一些 winRT 调用。除其他外,我想打开一个没有 GUI 界面的文件。
我使用来自 StorageFile 类的异步文件打开调用,因为下一个调用需要一个 IStorageFile 接口。
#include <roapi.h>
#include <winrt/Windows.Storage.h>
#include <winrt/Windows.Foundation.h>
void openFile()
{
using namespace winrt;
using namespace winrt::Windows::Foundation;
using namespace winrt::Windows::Storage;
HRESULT rtn = RoInitialize(RO_INIT_MULTITHREADED);
winrt::hstring path{ L"C:\\Users...\\mytextfile.txt"};
//wait for open the file
auto file = co_await StorageFile::GetFileFromPathAsync(path);
//IStorageFile interface needed
}
int main()
{
openFile();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
目前,编译器抱怨 co_await 表达式需要一个合适的“await_ready”函数,但没有找到。
我不确定是否是由于缺少标头包含或在 win32 应用程序中无法使用“co_await”而导致的这种情况。
编辑:我的 Visual Studio 项目设置是: - 使用 c++17,将 cppwinrt.exe 添加到我的包含目录,链接到 windowsapp.lib 并使用 windows sdk 版本 10.0.17134.0。
问题是该openFile()函数没有正确的返回类型来处理co_await。
请参阅我为C++11 线程创建的答案中的研究和工作,以更新 MFC 应用程序窗口。需要 SendMessage(), PostMessage() 吗?其中包含对协程的各种方法的建议列表。
这个问题是关于将 C++/WinRT 与 MFC 一起使用,但该材料也适用于 WinAPI。
另请参阅将 SDK 与 Windows 10 更新同步以及将 WinRT 与标准 C++ 一起使用,其中包含一个简单的控制台应用程序示例,该示例使用 Web 联合异步功能从 RSS 源检索 URL 列表。有许多文档链接,其中一些现在有点过时了。
附录:示例控制台应用程序
我使用 Visual Studio 2017 创建了以下简单的控制台应用程序。我创建了文本文件,然后在调试器中运行它。然后我重命名了文本文件并在调试器中再次运行它,并且由于具有该名称的文件不再存在而引发了异常。
另请参阅C++/WinRT,Windows SDK 17134 的一部分与 Visual Studio 15.8 预览版 3 不兼容,其中描述了您可能需要更改的编译器选项。我做到了。
// console_winrt.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
// Requires the following changes to the project properties in the C++ compiler section.
// - C++ language standard must be set to C++17
// - Add /await to the Additional options
#include "pch.h"
#pragma comment(lib, "windowsapp")
#include <winrt/Windows.Storage.h>
#include <winrt/Windows.Foundation.h>
#include <iostream>
winrt::Windows::Foundation::IAsyncAction openMyFile()
{
winrt::hstring path{ L"D:\\Users\\rickc\\mytextfile.txt" };
//wait for open the file
auto file = co_await winrt::Windows::Storage::StorageFile::GetFileFromPathAsync(path);
//IStorageFile interface needed
auto xDate = file.DateCreated();
std::cout << "file was found " << std::endl;
}
int main()
{
// initialize the WinRT apartment.
winrt::init_apartment();
auto x = openMyFile();
// wait on the file access since that is all we are doing and we need to give it time.
x.get();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我使用了以下属性设置。
| 归档时间: |
|
| 查看次数: |
1560 次 |
| 最近记录: |