linux版本微信打开关闭快捷键
安装相关依赖:
sudo apt install libx11-dev libdbus-1-dev wmctrl
复制源代码,编译:
g++ -std=c++11 -o wechat wechat.cpp
deepin系统设置全局快捷键

源码:
//g++ -std=c++11 -o wechat wechat.cpp
//这是一个通过alt+w实现微信显示和隐藏的c++语言程序
//sudo apt install wmctrl
//libx11-dev libdbus-1-dev
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>
class WeChatController {
private:
std::vector<std::string> executeCommand(const std::string& cmd) {
std::vector<std::string> result;
FILE* pipe = popen(cmd.c_str(), "r");
if (!pipe) return result;
char buffer[128];
while (fgets(buffer, sizeof(buffer), pipe) != nullptr) {
std::string line(buffer);
if (!line.empty() && line.back() == '\n') {
line.pop_back();
}
result.push_back(line);
}
pclose(pipe);
return result;
}
std::string getWeChatPid() {
auto pids = executeCommand("pgrep -x wechat");
return pids.empty() ? "" : pids[0];
}
std::vector<std::string> getWeChatWindows() {
return executeCommand("xdotool search --class 'wechat'");
}
std::string getActiveWindow() {
auto windows = executeCommand("xdotool getactivewindow");
return windows.empty() ? "" : windows[0];
}
void activateWeChatTrayIcon() {
std::string wechat_pid = getWeChatPid();
if (wechat_pid.empty()) {
exit(1);
}
auto items = executeCommand("qdbus org.kde.StatusNotifierWatcher /StatusNotifierWatcher org.kde.StatusNotifierWatcher.RegisteredStatusNotifierItems");
for (const auto& item : items) {
if (item.find(wechat_pid) != std::string::npos) {
size_t pos = item.find('/');
if (pos != std::string::npos) {
std::string item_name = item.substr(0, pos);
std::string cmd = "dbus-send --session --type=method_call --dest=\"" +
item_name + "\" /StatusNotifierItem org.kde.StatusNotifierItem.Activate int32:0 int32:0";
system(cmd.c_str());
break;
}
}
}
}
public:
void run() {
// 获取微信窗口和当前活动窗口
auto wechat_windows = getWeChatWindows();
std::string current_window = getActiveWindow();
bool found = false;
std::string active_wechat_window;
// 检查当前活动窗口是否是微信窗口
for (const auto& window_id : wechat_windows) {
if (current_window == window_id) {
found = true;
active_wechat_window = window_id;
break;
}
}
// 切换逻辑
if (found) {
// 微信窗口是当前活动窗口,关闭它
if (system("which wmctrl > /dev/null 2>&1") == 0) {
std::string cmd = "wmctrl -ic " + active_wechat_window;
system(cmd.c_str());
} else {
// 备用方案:发送 Alt+F4
std::string cmd = "xdotool key --window " + active_wechat_window + " alt+F4";
system(cmd.c_str());
}
} else {
// 微信窗口不是当前活动窗口,激活第一个微信窗口
if (!wechat_windows.empty()) {
std::string cmd = "xdotool windowactivate " + wechat_windows[0];
system(cmd.c_str());
activateWeChatTrayIcon();
} else {
std::cout << "未找到微信窗口" << std::endl;
}
}
}
};
int main() {
WeChatController controller;
controller.run();
return 0;
}
浙公网安备 33010602011771号