Dean Bates
Dean Bates

Reputation: 1957

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

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

Upvotes: 13

Views: 53357

Answers (3)

using System.Runtime.InteropServices;
public partial class NativeMethods
{        
    [DllImport("user32.dll", EntryPoint = "BlockInput")]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool BlockInput([MarshalAs(UnmanagedType.Bool)] bool fBlockIt);
}

internal is not public. So it does not fall into the CA1401

A public or protected method in a public type has the System.Runtime.InteropServices.DllImportAttribute attribute

Upvotes: 0

JaredPar
JaredPar

Reputation: 754763

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

Upvotes: 23

Josh Stodola
Josh Stodola

Reputation: 82483

Look into the BlockInput Win32 function

Sounds like some fun testing :)

Upvotes: 7

Related Questions