Ignoring queued mouse events

你。 提交于 2019-12-03 07:04:40

Disabling the controls won't help you, as I've found from my POS application that the users can sneak in another click in about 50ms, especially when using a touch screen that is not calibrated.

One of the problems this creates is when producing an invoice, you can't have a duplicate click produce another invoice, just because there's a 50ms delay before clearing the current invoice.

In cases like this, I use a pattern similar to this:

    public static void ClearMouseClickQueue()
    {
        Message message;
        while (PeekMessage(out message,IntPtr.Zero, (uint) MessageCodes.WM_MOUSEFIRST,(uint) MessageCodes.WM_MOUSELAST,1) != 0)
        {    
        }
    }

    private object approvalLockObject = new object();

    private void btnApproveTransaction_Click(object sender, EventArgs e)
    {
        ApproveTransactionAndLockForm();
    }

    private void ApproveTransactionAndLockForm()
    {
        lock (approvalLockObject)
        {
            if (ApprovalLockCount == 0)
            {
                ApprovalLockCount++;
                ApproveTransaction();
            }
            else
            {
                CloseAndRetry();
            }
        }
    }

    private void ApproveTransaction()
    {
        ClearMouseClickQueue();

        this.Enabled = false;

        Logger.LogInfo("Before approve transaction");

        MouseHelper.SetCursorToWaitCursor();

        ... validate invoice and print
    }

In case you need to reenable the screen, do this:

            this.Enabled = true;

            ApprovalLockCount = 0;

            DialogResult = DialogResult.None;

I believe that the best solution is to prevent the events from happening. You can do that by disabling all the controls and re-enabling them, when the lengthy operation finishes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!