实现 WaitForMouseUp() 函数的更好方法? [英] A Better Way to Implement a WaitForMouseUp() Function?

查看:22
本文介绍了实现 WaitForMouseUp() 函数的更好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个小函数来等待鼠标左键被释放,并且不会基于MouseUp 事件.

I needed a small function that will wait for the left mous button to be released, and will not be based on the MouseUp event.

在许多情况下,当我们需要这样做时,我们只需为 MouseUp 事件 编写一个事件处理程序.
这很简单,而且很有效.

In many cases when we need this, we simply write an event handler for the MouseUp event.
It's simple, and it works.

但是在某些情况下,使用 MouseUp 事件 将没有用,
例如,当我们已经在另一个(不同的)事件处理程序中时,
并且在调用此事件处理程序时可能会按下鼠标左键,我们需要等待它被释放.(目标是拥有单一的代码流,而不必将其拆分到多个可能已经被其他代码占用的地方)

There are however cases, where using the MouseUp event will not be useful,
such as when we are already in another (different) event handler,
and the left mouse button might be pressed when this event handler is called, and we need to wait for it to be released. (the goal is to have a single flow of code, and not have to split it between several places which might already be occupied with another code)

我是这样实现的:

public void WaitForMouseUp()
{
    while( (Control.MouseButtons&MouseButtons.Left)!=0 )
        Application.DoEvents();
}

它有效,
例如,您可以在 Control.Enter 事件的事件处理程序中使用它,
如果控件是通过鼠标输入的,则该函数将阻塞,直到释放鼠标按钮.

It works,
you can use it for example when you are in the event handler for the Control.Enter event,
and if the control was entered via the mouse, then this function will block until the mouse button is released.

我只担心一件事:
我在那里使用 Application.DoEvents(),我想知道是否有另一种方法来代替使用 Application.DoEvents().(Application.DoEvents(); 有可能重入的缺点,因此,出于这个原因,我尽量减少使用它,只要可能)

I only worry about one thing:
I am using Application.DoEvents() there, and I wonder if there another way instead of using Application.DoEvents(). (Application.DoEvents(); has disadvantages of possible reentrancy, and so, so for this reason I try to minimize using it, whenever possible)

有人知道我可以用什么代替 Application.DoEvents() 部分吗?

Anyone has an idea with what I can substitute the Application.DoEvents() part?

推荐答案

如果您不想在单个方法中编写流程,您可以使用 TaskCompletionSource 制作一个可等待的.

If You wan't to write a flow within a single method, you can make an awaitable using a TaskCompletionSource.

您的流程:

await MouseUp();

...

private Task MouseUp() {
  _tcs = new TaskCompletionSource();
  return _tcs.Task;
}

public ... OnMouseUpEvent() {
  _tcs?.SetResult(true);
}

对不起,伪代码,一旦我得到手机以外的东西,我会更新这个.

Sorry for Pseudo code, will update this once I get something other than a mobile.

OT:评论者:跳出框框思考!

OT: Commenters: Think outside of the Box!

这篇关于实现 WaitForMouseUp() 函数的更好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆