0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

cscの作法 その278

Posted at

概要

cscの作法、調べてみた。
練習問題やってみた。

練習問題

SetWindowsHookEx使ってください。

方針

マウスやる。

サンプルコード

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;

class MyHook {
	[DllImport("user32.dll")]
	public static extern IntPtr CallNextHookEx(IntPtr hHook, int nCode, IntPtr wParam, IntPtr lParam);
	[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
	static extern IntPtr SetWindowsHookEx(int idHook, delegateHookCallback lpfn, IntPtr hMod, uint dwThreadId);
	[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
	[return: MarshalAs(UnmanagedType.Bool)]
	static extern bool UnhookWindowsHookEx(IntPtr hhk);
	[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
	static extern IntPtr GetModuleHandle(string lpModuleName);
	delegate IntPtr delegateHookCallback(int nCode, IntPtr wParam, IntPtr lParam);
	IntPtr hookPtr = IntPtr.Zero;
	public void Hook() {
		using (Process curProcess = Process.GetCurrentProcess())
		using (ProcessModule curModule = curProcess.MainModule)
		{
			hookPtr = SetWindowsHookEx(14, HookCallback, GetModuleHandle(curModule.ModuleName), 0);
		}
	}
	private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) {
		if ((long) wParam == 0x0201) 
		{
			var p = Cursor.Position;
			Console.Write(p.X);
			Console.Write(", ");
			Console.WriteLine(p.Y);
		}
		return CallNextHookEx(hookPtr, nCode, wParam, lParam);
	}
	public void HookEnd() {
		UnhookWindowsHookEx(hookPtr);
		hookPtr = IntPtr.Zero;
	}
}
class SampleKeyHook {
	static void Main(string[] args) {
		MyHook myHook = new MyHook();
		myHook.Hook();
		Application.Run();
		myHook.HookEnd();
	}
}





以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?