Skip to content

Instantly share code, notes, and snippets.

@Heinrich-XIAO
Last active September 10, 2024 23:52
Show Gist options
  • Save Heinrich-XIAO/af1ba9df0ec41ce2acb7295cf1fccfb6 to your computer and use it in GitHub Desktop.
Save Heinrich-XIAO/af1ba9df0ec41ce2acb7295cf1fccfb6 to your computer and use it in GitHub Desktop.
A simple c++ script to send a notification cross-platform.
#include <iostream>
#include <string>
#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#elif defined(__APPLE__)
#include <unistd.h>
#include <sys/wait.h>
#elif defined(__linux__)
#include <unistd.h>
#include <sys/wait.h>
#endif
#if defined(__APPLE__) || defined(__linux__)
void sendLinuxNotification(const std::string &title, const std::string &message) {
pid_t pid = fork();
if (pid == 0) {
execlp("notify-send", "notify-send", title.c_str(), message.c_str(), (char *) NULL);
_exit(1);
} else if (pid > 0) {
wait(NULL);
}
}
void sendMacNotification(const std::string &title, const std::string &message) {
pid_t pid = fork();
if (pid == 0) {
execlp("osascript", "osascript", "-e",
("display notification \"" + message + "\" with title \"" + title + "\"").c_str(),
(char *) NULL);
_exit(1);
} else if (pid > 0) {
wait(NULL);
}
}
#endif
void sendNotification(const std::string &title, const std::string &message) {
#if defined(_WIN32) || defined(_WIN64)
MessageBox(0, message.c_str(), title.c_str(), MB_OK | MB_ICONINFORMATION);
#elif defined(__APPLE__)
sendMacNotification(title, message);
#elif defined(__linux__)
sendLinuxNotification(title, message);
#else
std::cerr << "Unsupported platform!" << std::endl;
#endif
}
int main() {
sendNotification("Hello", "This is a notification");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment