• ubuntu Setforeground 前台应用切换


    场景分析

    有这样一个系统,一个服务主进程用于接收指令,其它服务是独立的gui 程序,服务进程根据命令将对应的gui 程序切换到前台。

    windows 平台有Setforeground 这个api,可以根据进程ID,将某个应用的窗口切换到前台。ubuntu 并没有类似的api, 这里借助xdotool 这个第三方库,实现类似的功能。

    xdotool git clone 后,直接make,生成动态库libxdo 和执行程序程序 xdotool。

    需求

    SetForeGround 大概就是根据进程ID,并激活该窗口为前台窗口。用xdotool 命令实现如下

    1. xdotool search --pid 进程ID
    2. #返回窗口id
    3. xdotool windowactivate 窗口ID

     search 返回的ID 如果有多个,是因为一个进程有多个窗口,需要根据窗口标题再筛选

    实际应用中,一般直接调用库,代码实现如下:

    1. bool SetForeground(uint32_t pid, const char* window_name)
    2. {
    3. Window *list = NULL;
    4. unsigned int nwindows;
    5. xdo_search_t search;
    6. xdo_t *context = xdo_new(NULL);
    7. memset(&search, 0, sizeof(xdo_search_t));
    8. search.max_depth = -1;
    9. search.require = xdo_search::SEARCH_ANY;
    10. search.pid = pid;
    11. search.searchmask = SEARCH_PID;
    12. do
    13. {
    14. if(list != NULL)
    15. {
    16. free(list);
    17. }
    18. xdo_search_windows(context, &search, &list, &nwindows);
    19. if(nwindows > 0)
    20. {
    21. for(int i = 0;i < nwindows;i++)
    22. {
    23. unsigned char *name;
    24. int name_len;
    25. int name_type;
    26. xdo_get_window_name(context, list[i], &name, &name_len, &name_type);
    27. QString window_name((char*)name);
    28. if(window_name == window_name)
    29. {
    30. xdo_activate_window(context, list[i]);
    31. }
    32. }
    33. }
    34. usleep(500000);
    35. }while(nwindows == 0);
    36. if(list != NULL)
    37. {
    38. free(list);
    39. }
    40. xdo_free(context);
    41. return true;
    42. }
    43. //调用:
    44. SetForeground(QCoreApplication::applicationPid(), this->windowTitle().toStdString().c_str());

    注:这个只适用于x11 图形平台,wayland 可能存在问题。

  • 相关阅读:
    springboot+清远旅游推荐网站 毕业设计-附源码211551
    mybatis逆向工程的构建及其概念
    You Are Given a Decimal String..(最短路,思维)
    RK3568平台开发系列讲解(基础篇)内核是如何发送事件到用户空间
    Rsync远程同步
    【题解】同济线代习题一.8.6
    WebRTC 如何指定 H265解码器
    c++入门99题41-50
    寒假作业2月6号
    Python转换文件夹中的图片格式
  • 原文地址:https://blog.csdn.net/sinat_27720649/article/details/134470191