如何通过C++ Win32原生API在Windows 10日历中注册新事件或提醒?
在Windows 10中用原生C++添加日历事件/提醒的方法
Windows 10的日历功能对应的原生API属于Windows Runtime (WinRT) 范畴,原生C可以通过C/WinRT(微软推荐的现代C++调用WinRT的方式)实现事件/提醒的添加,以下是具体实现方案:
一、项目配置
确保你的C项目支持C/WinRT:
- 在Visual Studio中安装「C++/WinRT扩展」;
- 新建项目时选择「C++/WinRT Windows Desktop Application」,或在现有项目属性中启用C++/WinRT支持。
二、UI交互式添加(唤起系统日历界面)
这种方式会弹出系统自带的日历添加窗口,由用户确认后完成添加,无需额外权限:
核心代码示例
#include <winrt/Windows.ApplicationModel.Appointments.h> #include <winrt/Windows.Foundation.h> #include <windows.h> int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow) { // 初始化WinRT运行时环境 winrt::init_apartment(); // 创建日历事件对象 winrt::Windows::ApplicationModel::Appointments::Appointment appointment; // 设置事件核心属性 appointment.Subject(L"团队周会"); appointment.Location(L"1号会议室"); appointment.Details(L"讨论Q3项目进度与风险"); // 设置开始时间(当前时间+1小时) auto startTime = winrt::Windows::Foundation::DateTime::clock::now() + std::chrono::hours(1); appointment.StartTime(startTime); // 设置时长(60分钟) appointment.Duration(std::chrono::minutes(60)); // 获取窗口句柄(可替换为你的应用窗口句柄) HWND hWnd = GetDesktopWindow(); // 唤起系统日历添加界面,同步等待结果 bool isAdded = appointment.ShowAddAppointmentAsync(reinterpret_cast<HWND>(hWnd)).get(); MessageBoxW(hWnd, isAdded ? L"日历事件添加成功!" : L"添加取消或失败!", L"操作提示", MB_OK); return 0; }
三、静默式添加(后台直接写入日历)
若需无需用户交互直接添加事件,需使用AppointmentStore API,同时需要配置权限:
1. 配置权限
在项目的Package.appxmanifest中添加日历权限声明:
<Capabilities> <Capability Name="appointments" /> </Capabilities>
2. 核心代码示例
#include <winrt/Windows.ApplicationModel.Appointments.h> #include <winrt/Windows.Foundation.h> #include <windows.h> int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow) { winrt::init_apartment(); winrt::Windows::ApplicationModel::Appointments::Appointment appointment; appointment.Subject(L"自动添加的测试提醒"); appointment.StartTime(winrt::Windows::Foundation::DateTime::clock::now() + std::chrono::hours(2)); appointment.Duration(std::chrono::minutes(15)); // 请求日历存储的读写权限 auto store = winrt::Windows::ApplicationModel::Appointments::AppointmentManager::RequestStoreAsync( winrt::Windows::ApplicationModel::Appointments::AppointmentStoreAccessType::AppCalendarsReadWrite).get(); // 添加事件到用户默认日历 winrt::hstring appointmentId = store.CreateAppointmentAsync(appointment).get(); HWND hWnd = GetDesktopWindow(); MessageBoxW(hWnd, appointmentId.empty() ? L"静默添加失败!" : L"静默添加成功!", L"操作提示", MB_OK); return 0; }
注意事项
- 需链接
runtimeobject.lib,C++/WinRT项目会自动处理该依赖; - 静默添加方式首次运行时会弹出权限请求窗口,需用户同意后才能生效;
- 所有时间相关操作基于
std::chrono,需确保项目支持C++11及以上标准。
内容的提问来源于stack exchange,提问作者IMAN4K
相关产品推荐
相关产品推荐

