top of page
Search

Preventing Key Stroke in C#

  • Yogesh Kumar
  • Jan 10, 2017
  • 2 min read

Hey Dear! This is Yogesh Kumar.

Well this is my first Blog. The aim is, in many cases I found that I want, no one can use my Lappy’s keyboard while I’m doing some important work on my lappy. The reason is, my nephew is there who comes suddenly and hit on my lappy’s keyboard. Many times I lost some data due to this reason. So I decided to prevent my lappy’s keyboard from being press.

NOTE: We will discuss about how to prevent a user of the application from being pressed a specific key of the keyboard.

Using SuppressKeyPress

Suppress means preventing. And the SuppressKeyPress is a property which gets or sets a value that indicate whether the key event should be passed on to the underlaying control or not. Here the underlaying control means ‘Event Handler’ which occur when the key is press. The SuppressKeyPress property lies under the KeyEventArgs class of the System.Windows.Forms namespace.

Syntex:

public bool SuppressKeyPress { get; set; }

Property value:

Type: System.Boolean

‘ true’ if the key should not be sent to the control, otherwise ‘false’.

NOTE: You can assign ‘true’ to this property in an event handler such as ‘KeyDown’ in order to prevent user input.

Just set e.SuppressKeyPress = true (in KeyDown event) when you want to suppress a key stroke.

Example: In the example below we will discuss about how to prevent a user to use the ‘Backspace’ key.

Step 1: Open the Visual Studio and create a new Project of Windows Form type and name it as ‘PreventInput’.

Step 2: From the left side ToolBox pane, drag and drop a textBox onto the form.

Step 3: Now select the textBox and open its Property window, which will appear on right hand side.

Step 4: In the Property window click on the lightning bolt symbol.

Step 5: Now you can see all the available events to the textBox control. Here find and double click on the KeyDown event.

Step 6: Now write the code as described below:

if ( e.KeyCode == keys.Back )

{

e.SuppressKeyPress = true ; //prevent the key to work

}

The entire code is as follow:

using System.Windows.Form; //includes required library

namespace PreventInput //namespace

{

public partial class Form1 : Form //main class, inherits from base class

{

public Form1() //constructor

{

InitializeComponents();

}

// Start KeyDown Event

private void textBox1_KeyDown(Object sender, KeyEventArgs e)

{

if (e.KeyCode == keys.Back) //if key is backspace

{

e.SuppressKeyPress = true ; //sets SuppressKeyPress to true

} //end if statement

} //end KeyDown event

} // end main class

} //end namespace

Comments


bottom of page