XCB_POLL_FOR_EVENT未检测到关闭窗口的XCB_CLIENT_MESSAGE事件

xcb_poll_for_event does not detect XCB_CLIENT_MESSAGE event for closing window

本文关键字:XCB 窗口 MESSAGE 事件 CLIENT FOR POLL EVENT 检测      更新时间:2023-10-16

我正在将应用程序移植到Linux,并且我正在使用XCB库进行窗口处理。我需要检测窗口何时关闭,以便应用程序可以退出。但是,由于系统的设计方式,系统无法阻止主窗口循环。这在Windows中很容易,因为您只使用PeekMessage。但是,当我尝试使用xcb_poll_for_event检测XCB_CLIENT_MESSAGE时,XCB似乎不起作用。当我尝试注入WM_DELETE_WINDOW协议时,窗口上的关闭按钮实际上没有功能。

窗口设置:

// initialize XCB
this->connection = xcb_connect(NULL, NULL);
this->screen = xcb_setup_roots_iterator(xcb_get_setup(this->connection)).data;;
// create window
u32 mask = 0;
u32 values[1];
this->window = xcb_generate_id(this->connection);
mask = XCB_CW_EVENT_MASK;
values[0] = XCB_EVENT_MASK_EXPOSURE;
xcb_create_window(this->connection, 0, this->window, this->screen->root, 0, 0, width, height, 0, XCB_WINDOW_CLASS_INPUT_OUTPUT, this->screen->root_visual, mask, values);
// setup close handler event
xcb_intern_atom_cookie_t protocolCookie = xcb_intern_atom_unchecked(this->connection, 1, 12, "WM_PROTOCOLS");
xcb_intern_atom_reply_t* protocolReply = xcb_intern_atom_reply(this->connection, protocolCookie, 0);
xcb_intern_atom_cookie_t closeCookie = xcb_intern_atom_unchecked(this->connection, 0, 16, "WM_DELETE_WINDOW");
this->m_closeReply = xcb_intern_atom_reply(this->connection, closeCookie, 0);
xcb_change_property(this->connection, XCB_PROP_MODE_REPLACE, this->window, protocolReply->atom, 4, 32, 1, &(this->m_closeReply->atom));
free(protocolReply);
// map and flush
xcb_map_window(this->connection, this->window);
xcb_flush(this->connection);

消息循环:

// handle all incoming messages
xcb_generic_event_t* e;
while(e = xcb_poll_for_event(connection))
{
    // take action from message
    switch(e->response_type & ~0x80)
    {
        case XCB_EXPOSE:
            // invalidated
            xcb_flush(connection);
            break;
        case XCB_CLIENT_MESSAGE:
            // close window
            if(((xcb_client_message_event_t*)e)->data.data32[0] == (*this->m_closeReply).atom)
                return false;
            break;
    }
    // cleanup
    free(e);
}

窗口关闭时,当我用xcb_wait_for_event替换xcb_poll_for_event时,窗口关闭的作品是完美的,但是在等待消息时,窗口循环被阻止。我只需要知道我在使用xcb_poll_for_event时永远不会检测到的事件。

永远不会被检测到

来自XCB教程

注意:一个常见的错误程序员确实是添加代码以处理其程序中的新事件类型,同时忘记在创建窗口中为这些事件添加蒙版。这样的程序员应该坐下几个小时来调试他的程序,想知道"为什么我的程序不通知我发布了按钮?"只是为了发现他们注册了按钮按下按钮事件,但没有用于按钮发布事件。<<<<<。/p>

和您的代码

mask = XCB_CW_EVENT_MASK;
values[0] = XCB_EVENT_MASK_EXPOSURE;
xcb_create_window(
  this->connection,
  0,
  this->window,
  this->screen->root,
  0, 0,
  width, height,
  0,
  XCB_WINDOW_CLASS_INPUT_OUTPUT,
  this->screen->root_visual,
  mask, values  // <--
);

您已经告诉X服务器仅向您发送某些事件,而您忽略了包括XCB_EVENT_MASK_STRUCTURE_NOTIFY

- values[0] = XCB_EVENT_MASK_EXPOSURE;
+ values[0] = XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;