如何在 C# 中阻止键盘和鼠标输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/586547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 09:17:29  来源:igfitidea点击:

How can I block keyboard and mouse input in C#?

c#windowskeyboardmouse

提问by Dean Bates

I'm looking for some code (preferably C#) that will prevent keyboard and mouse input.

我正在寻找一些防止键盘和鼠标输入的代码(最好是 C#)。

回答by Josh Stodola

Look into the BlockInputWin32 function

查看BlockInputWin32 函数

Sounds like some fun testing :)

听起来像是一些有趣的测试:)

回答by JaredPar

Expanding on Josh's (correct) answer. Here's the PInvoke signature for that method.

扩展乔希的(正确)答案。这是该方法的 PInvoke 签名。

public partial class NativeMethods {

    /// Return Type: BOOL->int
    ///fBlockIt: BOOL->int
    [System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint="BlockInput")]
    [return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]
public static extern  bool BlockInput([System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)] bool fBlockIt) ;

}

public static void BlockInput(TimeSpan span) {
  try { 
    NativeMethods.BlockInput(true);
    Thread.Sleep(span);
  } finally {
    NativeMethods.BlockInput(false);
  }
}

EDIT

编辑

Added some code to demonstrate how to block for an interval

添加了一些代码来演示如何阻塞一段时间

回答by Allan Simonsen

Have a look at this article Processing Global Mouse and Keyboard Hooks in C#. The guy who wrote this article have done alot of research around the problem.

看看这篇文章用 C# 处理全局鼠标和键盘挂钩。写这篇文章的人围绕这个问题做了很多研究。

Maybe there is somthing in it you can use.

也许里面有你可以使用的东西。