添加按钮以通知运行函数的通知

Add buttons to libnotify notifications that run functions

本文关键字:通知 函数 运行 添加 按钮      更新时间:2023-10-16

我需要在libnotice通知的底部添加按钮,以便在单击时运行功能。我可以显示按钮,但它们在单击时不会运行这些功能。它根本不提供任何错误消息。

该程序的调用方式为./notifications "Title" "Body" "pathtoicon"

法典:

#include <libnotify/notify.h>
#include <iostream>
void callback_mute(NotifyNotification* n, char* action, gpointer user_data) {
std::cout << "Muting Program" << std::endl;
system("pkexec kernel-notify -am");
}
int main(int argc, char * argv[] ) {
GError *error = NULL;
notify_init("Basics");
NotifyNotification* n = notify_notification_new (argv[1],
argv[2],
argv[3]);
notify_notification_add_action (n,
"action_click",
"Mute",
NOTIFY_ACTION_CALLBACK(callback_mute),
NULL,
NULL);

notify_notification_set_timeout(n, 10000);
if (!notify_notification_show(n, 0)) {
std::cerr << "Notification failed" << std::endl;
return 1;
}
return 0;
}

任何帮助将不胜感激,谢谢!

你必须使用GMainLoop,一个"主事件循环"才能使回调函数工作。libnotify使用此循环来处理其操作,如果没有它,它根本不会调用您期望的回调函数,因为没有任何处理它。

基本上在你的main函数中,只需在开始时添加一个GMainLoop *loop,然后loop = g_main_loop_new(nullptr, FALSE);初始化它,最后只需添加g_main_loop_run(loop);。您的程序应该像以前一样运行,但回调函数现在可以工作了。所以基本上:

int main(int argc, char **argv)
{
GMainLoop *loop;
loop = g_main_loop_new(nullptr, FALSE);
// ... do your stuff
g_main_loop_run(loop);
return 0;
}

您可以在以下位置阅读有关它的更多信息:主事件循环:GLib 参考手册

您不必包含glib.h因为无论如何libnotify都包含它。