今天闲着无聊,试着用C#写查看密码框的程序(不仅限于密码框,应该是任何有文本的控件都可以)
代码见下面.
用C++实现起来超简单的这么个东东..用C#复杂得很,我又不想用unsafe,我总觉得用unsafe的话,干嘛不干脆用C++算了.
int Length=300;
IntPtr THandle=APIs.GetLocalWindow();//取得当前鼠标所在位置的控件句柄
int Address=APIs.VirtualAllocEx(Process.GetCurrentProcess().Handle,0,Length,0x1000,0x04);//在本进程内分配Length大小的内存
APIs.SendMessage(THandle,0x000D,new IntPtr(255),new IntPtr(Address));//发送消息到目标控件,0x000D就是WM_GETTEXT,255的意思是保存返回的值,new IntPtr(Address)是指保存到Address指定的地址
byte[] buf=new byte[Length];
APIs.ReadProcessMemory(Process.GetCurrentProcess().Handle,Address,buf,Length,0);//读取刚才保存的内容
MessageBox.Show(Encoding.Default.GetString(buf));//显示出来测试一下.
其中APIs开头的,是我自己写的API类库,相关声明如下:
[DllImport("user32.dll")]
public static extern IntPtr WindowFromPoint(
POINT lpPoint
);
[DllImport("user32.dll")]
public static extern int GetCursorPos(
out POINT lpPoint
);
public static IntPtr GetLocalWindow()//这个只是把上两个结合了一下
{
POINT point;
GetCursorPos(out point);
return WindowFromPoint(point);
}
//不加Ex的话.上面就不用第一个Handle参数了
[ DllImport( "Kernel32.dll" )]
public static extern System.Int32 VirtualAllocEx(
System.IntPtr hProcess,
System.Int32 lpAddress,
System.Int32 dwSize,
System.Int16 flAllocationType,
System.Int16 flProtect
);
[DllImport("User32.dll")]
public static extern IntPtr SendMessage(
IntPtr hWnd,
int Msg,
IntPtr wParam,
IntPtr lParam
);
[ DllImport( "Kernel32.dll" )]
public static extern int ReadProcessMemory(
System.IntPtr hProcess,
System.Int32 lpBaseAddress,
byte[] lpBuffer,
long nSize,
long lpNumberOfBytesWritten
);
*******************************************************************
因为一般要查看的是外部程序,配合快捷键不失不一种好方法.
C#的实现如下:
在初始化窗口的代码里加上
KeyModifiers modifiers=KeyModifiers.Windows;//定义为Win+快捷键,也可定义为别的.
RegisterHotKey(Handle, 1001,modifiers,Keys.V);//给Win+V分配ID为1001
override一下WndProc
protected override void WndProc( ref Message m )
{
const int WM_HOTKEY = 0x0312;
switch(m.Msg)
{
case WM_HOTKEY:
switch (m.WParam.ToInt32())
{
case 1001:
OnHotKeyV();
break;
default:break;
}
break;
}
base.WndProc(ref m );
}
在OnHotKeyV函数里写上我最开始写的那段代码就可以了.