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

2019-01-09 07:03发布

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

3条回答
在下西门庆
2楼-- · 2019-01-09 07:29

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

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

查看更多
一夜七次
3楼-- · 2019-01-09 07:29

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.

Maybe there is somthing in it you can use.

查看更多
We Are One
4楼-- · 2019-01-09 07:52

Look into the BlockInput Win32 function

Sounds like some fun testing :)

查看更多
登录 后发表回答