0

I have problem with my sleep function in C.

When i use in this code sleep function like this:

while(1) {
        XNextEvent(display, &xevent);
        switch (xevent.type) {
            case MotionNotify:
                break;
            case ButtonPress:
                printf("Button click: [%d, %d]\n", xevent.xmotion.x_root, xevent.xmotion.y_root);
                sleep(5);
                break;
            case ButtonRelease:
                break;
        }

It doesn't works well for me because printf("button click") is executing all time but slower.

How to print "button click x y" once and stop listening for click for 5 second?

Adrian
  • 532
  • 1
  • 7
  • 16
  • 1
    It's not clear to me what you want - `sleep`ing in the event loop is not what X was made for. – tofro Jun 18 '17 at 22:37
  • When I click anywhere on my screen i get message "button click x,y" When I click fast 5 times I get 5 messages but after 25 second. I wish to get only one message even if i several times. – Adrian Jun 18 '17 at 22:49

1 Answers1

2

I think you're looking for something like:

/* ignore_click is the time until mouse click is ignored */
time_t ignore_click = 0;

while(1) {
    XNextEvent(display, &xevent);
    switch (xevent.type) {
        case MotionNotify:
            break;
        case ButtonPress:
            {
                time_t now;
                /* we read current time */
                time(&now);

                if (now > ignore_click)
                {
                    /* now is after ignore_click, mous click is processed */
                    printf("Button click: [%d, %d]\n", xevent.xmotion.x_root, xevent.xmotion.y_root);

                    /* and we set ignore_click to ignore clicks for 5 seconds */
                    ignore_click = now + 5;
                }
                else
                {
                    /* click is ignored */
                }
            }
            break;
        case ButtonRelease:
            break;
    }
}

The code written above will ignore clicks for 4 to 5 seconds: the time_t type is a second precision structure...

To get more acurate time, you could use struct timeval or struct timespec structure. I do not use them in my example to keep it clear.

Mathieu
  • 8,840
  • 7
  • 32
  • 45