0

我正在尝试计算一个时间延迟来显示稳定的闪烁。我没有让它与sleep()or一起使用time.h,这似乎是合乎逻辑的。

我怎样才能实现类似的效果,显示一个白色矩形 10 秒,然后在循环中清除该区域(也是 10 秒)。

这个问题中,socket of the X11 connection提到了 a 来做这样的事情。但是,在这件事上,该往哪里挖呢?

谢谢

4

1 回答 1

0

文件描述符在 Display 结构中,可以通过宏获取ConnectionNumber(dis)

然后,您可以使用poll超时来等待事件到达或发生超时。

正如其他问题中提到的那样,XPending会让您查看是否有任何事件,因此您实际上不需要检查文件描述符,您可以执行以下操作:

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <time.h>
#include <unistd.h>

int main() 
{
    XEvent ev;
    Display *dis = XOpenDisplay(NULL);
    Window win = XCreateSimpleWindow(dis, RootWindow(dis, 0), 1, 1, 500, 500, 0, BlackPixel (dis, 0), WhitePixel(dis, 0));
    XMapWindow(dis, win);
    GC gc = XCreateGC(dis, win, 0, 0);
    int draw = 1;
    time_t t = time(NULL) + 10;

    XMapWindow(dis, win);

    XSelectInput(dis, win, ExposureMask | KeyPressMask);

    while (1)  
    {
        if (XPending(dis) > 0)
        {
            XNextEvent(dis, &ev);
            switch  (ev.type) 
            {
                case Expose:   
                printf("Exposed.\n");
                    if (draw > 0)
                {
                    XFillRectangle(dis, win, gc, 100, 100, 300, 300);
                }
                break;

                case KeyPress:
                printf("KeyPress\n");
                /* Close the program if q is pressed.*/
                if (XLookupKeysym(&ev.xkey, 0) == XK_q) 
                    {
                    exit(0);
                }
                break;
            }
        }
        else
        {
            printf("Pending\n");
            sleep(1);
            if (time(NULL) >= t)
            {
                /* Force an exposure */
            XClearArea(dis, win, 100, 100, 300, 300, True);
            t += 10;
            draw = 1 - draw;
            }
        }
    }

    return 0;
}

注意:您可能想要使用类似的东西usleep来获得更精细的计时器粒度。

于 2014-03-25T12:47:22.310 回答