Click here to Skip to main content
15,895,815 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am doing an application which will give some permissions to users.
I used what it said in this article here[^]
Thank you.
Here is what I did:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Security.Permissions;

using System.Windows.Forms;
using Microsoft.Win32;
using System.Diagnostics;
namespace UserControl
{
    class Control
    {
        [StructLayout(LayoutKind.Sequential)]
        private struct KBDLLHOOKSTRUCT
        {
            public Keys key;
            public int scanCode;
            public int flags;
            public int time;
            public IntPtr extra;
        }

        //System level functions to be used for hook and unhook keyboard input
        private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam);
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook,
            HookHandlerDelegate lpfn, IntPtr hMod, uint dwThreadId);
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool UnhookWindowsHookEx(IntPtr hook);
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
            IntPtr wParam, ref KBDLLHOOKSTRUCT lParam);
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string name);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern short GetAsyncKeyState(Keys key);


        //Declaring Global objects
        private static IntPtr ptrHook;
        //private static LowLevelKeyboardProc objKeyboardProcess;
        private static HookHandlerDelegate proc;
        private const int WH_KEYBOARD_LL = 13;

        private const int VK_CONTROL = 0x11;
        private const int WM_KEYUP = 0x0101;
        private const int WM_SYSKEYUP = 0x0105;
        [DllImport("user32.dll")]
        private static extern int FindWindow(string className, string windowText);

        [DllImport("user32.dll")]
        private static extern int ShowWindow(int hwnd, int command);

        [DllImport("user32.dll")]
        public static extern int FindWindowEx(int parentHandle, int childAfter, string className, int windowTitle);

        [DllImport("user32.dll")]
        private static extern int GetDesktopWindow();

        private const int SW_HIDE = 0;
        private const int SW_SHOW = 1;


        


        protected static int Handle
        {
            get
            {
                return FindWindow("Shell_TrayWnd", "");
            }
        }

        protected static int HandleOfStartButton
        {
            get
            {
                int handleOfDesktop = GetDesktopWindow();
                int handleOfStartButton = FindWindowEx(handleOfDesktop, 0, "button", 0);
                return handleOfStartButton;
            }
        }

        public Control()
        {
            proc = new HookHandlerDelegate(HookCallback);
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                ptrHook = SetWindowsHookEx(WH_KEYBOARD_LL, proc,
                   GetModuleHandle(curModule.ModuleName), 0);
            }
        }
        
        private static IntPtr HookCallback(int nCode, IntPtr wParam, ref KBDLLHOOKSTRUCT lParam)
        {
            //Filter wParam for KeyUp events only - otherwise this code
            //will execute twice for each keystroke (ie: on KeyDown and KeyUp)
            //WM_SYSKEYUP is necessary to trap Alt-key combinations
            if (nCode >= 0)
            {
                if (wParam == (IntPtr)WM_KEYUP || wParam == (IntPtr)WM_SYSKEYUP)
                {
                    //Raise the event

                } return (IntPtr)1;
                //Return a dummy value to trap the keystroke
               
            }
            //The event wasn't handled, pass it to next application
            return CallNextHookEx(ptrHook, nCode, wParam, ref lParam);
        }
        
        public static void Dispose()
        {
            UnhookWindowsHookEx(ptrHook);
        }
        public static void Hide()
        {

            proc = new HookHandlerDelegate(HookCallback);
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                ptrHook = SetWindowsHookEx(WH_KEYBOARD_LL, proc,
                   GetModuleHandle(curModule.ModuleName), 0);
            }

           
        }


    }

}


What I have tried:

I was able to disable all the keys but I need to disable specific keys and allow the letters and numeric keys in order to write.
Posted
Updated 13-Jul-16 22:16pm
v2
Comments
Richard MacCutchan 13-Jul-16 7:59am    
You just need to add some code to check which key was pressed and allow or not as required.
ZurdoDev 13-Jul-16 10:31am    
As Richard said, you first need to understand how that code works so then you can make an easy change to it.
TatsuSheva 13-Jul-16 10:54am    
I figured out a solution thank you.
ZurdoDev 13-Jul-16 20:22pm    
1. Reply to the comment so that the user is notified.
2. Please post something as a solution so that this question no longer shows as unanswered.

1 solution

Here is what I did.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Security.Permissions;

using System.Windows.Forms;
using Microsoft.Win32;
using System.Diagnostics;
namespace UserControl
{
    class Control
    {
        [StructLayout(LayoutKind.Sequential)]
        private struct KBDLLHOOKSTRUCT
        {
            public Keys key;
            public int scanCode;
            public int flags;
            public int time;
            public IntPtr extra;
        }

        //System level functions to be used for hook and unhook keyboard input
        private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int id, LowLevelKeyboardProc callback, IntPtr hMod, uint dwThreadId);
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool UnhookWindowsHookEx(IntPtr hook);
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hook, int nCode, IntPtr wp, IntPtr lp);
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string name);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern short GetAsyncKeyState(Keys key);


        //Declaring Global objects
        private static IntPtr ptrHook;
        private static LowLevelKeyboardProc objKeyboardProcess;

        private const int WH_KEYBOARD_LL = 13;
        private const int VK_CONTROL = 0x11;
        
        public Control()
        {
            ProcessModule objCurrentModule = Process.GetCurrentProcess().MainModule;
            objKeyboardProcess = new LowLevelKeyboardProc(captureKey);
            ptrHook = SetWindowsHookEx(13, objKeyboardProcess, GetModuleHandle(objCurrentModule.ModuleName), 0);
        }
        public static IntPtr captureKey(int nCode, IntPtr wp, IntPtr lp)
        {
            if (nCode >= 0)
            {
                KBDLLHOOKSTRUCT objKeyInfo = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lp, typeof(KBDLLHOOKSTRUCT));

                if (objKeyInfo.key == Keys.RControlKey || objKeyInfo.key == Keys.LControlKey || objKeyInfo.key == Keys.F4 || objKeyInfo.key == Keys.Alt || objKeyInfo.key == Keys.Tab || objKeyInfo.key == Keys.Delete) // Disabling Windows keys
                {
                    return (IntPtr)1;
                }
            }
            return CallNextHookEx(ptrHook, nCode, wp, lp);
        }
        
        public static void Dispose()
        {
            UnhookWindowsHookEx(ptrHook);
        }
        public static void Hide()
        {
           
            ProcessModule objCurrentModule = Process.GetCurrentProcess().MainModule;
            objKeyboardProcess = new LowLevelKeyboardProc(captureKey);
            ptrHook = SetWindowsHookEx(13, objKeyboardProcess, GetModuleHandle(objCurrentModule.ModuleName), 0);

           
        }


    }

}
 
Share this answer
 
Comments
Rajesh Nagaraj 12-Jun-21 9:18am    
Can You Please Help Me Where To Put The Above Code To Disable Hot Keys For My C# Form
This Helps Me For My Project.
Please Help Me, I'm A Newbie Here!!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;

namespace login_and_Register_System
{
public partial class frmRegister : Form
{
public frmRegister()
{
InitializeComponent();

}

readonly OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db_users.mdb");
OleDbCommand cmd = new OleDbCommand();
//readonly OleDbDataAdapter da = new OleDbDataAdapter();

private void button1_Click(object sender, EventArgs e)
{
if (txtUsername.Text == "" && txtPassword.Text == "" && txtComPassword.Text == "")
{
MessageBox.Show("Username and Password fields are empty", "Registration Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);

}
else if (txtPassword.Text == txtComPassword.Text)
{
con.Open();
string register = "INSERT INTO tbl_users VALUES ('" + txtUsername.Text + "','" + txtPassword.Text + "')";
cmd = new OleDbCommand(register, con);
cmd.ExecuteNonQuery();
con.Close();

txtUsername.Text = "";
txtPassword.Text = "";
txtComPassword.Text = "";

MessageBox.Show("Your Account has been Successfully Created", "Registration Success", MessageBoxButtons.OK, MessageBoxIcon.Information);

}
else
{
MessageBox.Show("Passwords does not match, Please Re-enter", "Registration Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtPassword.Text = "";
txtComPassword.Text = "";
txtPassword.Focus();
}
}

private void checkbxShowPas_CheckedChanged(object sender, EventArgs e)
{
if (checkbxShowPas.Checked)
{
txtPassword.PasswordChar = '\0';
txtComPassword.PasswordChar = '\0';
}
else
{
txtPassword.PasswordChar = '•';
txtComPassword.PasswordChar = '•';
}
}

private void button2_Click(object sender, EventArgs e)
{
txtUsername.Text = "";
txtPassword.Text = "";
txtComPassword.Text = "";
txtUsername.Focus();
}

private void label6_Click(object sender, EventArgs e)
{
new frmLogin().Show();
this.Hide();
}

private void frmRegister_Load(object sender, EventArgs e)
{
//label2.Text = kryptonDateTimePicker1.Value.ToShortDateString();
}

private void label2_Click(object sender, EventArgs e)
{

}

}
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900