首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

控制其他程序按钮?解决办法

2012-06-17 
控制其他程序按钮??我想写个程序控制其他程序的按钮,但是目标程序每次启动后系统给按钮分配的句柄都是不同

控制其他程序按钮??
我想写个程序控制其他程序的按钮,但是目标程序每次启动后系统给按钮分配的句柄都是不同的,所以保存句柄好像是行不通的。该怎么办?????

[解决办法]
楼主去看看C#提供的UIAutomation的类 里面就已经提供了相应的方法了
[解决办法]
例子:

C# code
using System.Runtime.InteropServices;[DllImport ( "user32.dll", EntryPoint = "FindWindow", SetLastError = true )]private static extern IntPtr FindWindow( string lpClassName, string lpWindowName );[DllImport ( "user32.dll", EntryPoint = "FindWindowEx", SetLastError = true )]private static extern IntPtr FindWindowEx( IntPtr hwndParent, uint hwndChildAfter, string lpszClass, string lpszWindow );[DllImport ( "user32.dll", EntryPoint = "SendMessage", SetLastError = true, CharSet = CharSet.Auto )]private static extern int SendMessage( IntPtr hwnd, uint wMsg, int wParam, int lParam );[DllImport ( "user32.dll", EntryPoint = "SetForegroundWindow", SetLastError = true )]private static extern void SetForegroundWindow( IntPtr hwnd );private void button1_Click( object sender, EventArgs e ){    const uint BM_CLICK = 0xF5; //鼠标点击的消息,对于各种消息的数值,大家还是得去API手册    IntPtr hwndCalc = FindWindow ( null, "计算器" ); //查找计算器的句柄    if ( hwndCalc != IntPtr.Zero )    {    IntPtr hwndThree = FindWindowEx ( hwndCalc, 0, null, "3" ); //获取按钮3 的句柄    IntPtr hwndPlus = FindWindowEx ( hwndCalc, 0, null, "+" );  //获取按钮 + 的句柄    IntPtr hwndTwo = FindWindowEx ( hwndCalc, 0, null, "2" );  //获取按钮2 的句柄    IntPtr hwndEqual = FindWindowEx ( hwndCalc, 0, null, "=" ); //获取按钮= 的句柄    SetForegroundWindow ( hwndCalc );    //将计算器设为当前活动窗口    System.Threading.Thread.Sleep ( 2000 );   //暂停2秒让你看到效果    SendMessage ( hwndThree, BM_CLICK, 0, 0 );    System.Threading.Thread.Sleep ( 2000 );   //暂停2秒让你看到效果    SendMessage ( hwndPlus, BM_CLICK, 0, 0 );    System.Threading.Thread.Sleep ( 2000 );   //暂停2秒让你看到效果    SendMessage ( hwndTwo, BM_CLICK, 0, 0 );    System.Threading.Thread.Sleep ( 2000 );   //暂停2秒让你看到效果    SendMessage ( hwndEqual, BM_CLICK, 0, 0 );    System.Threading.Thread.Sleep ( 2000 );    MessageBox.Show ("你看到结果了吗?");    }    else    {    MessageBox.Show ("没有启动 [计算器]");    }}
[解决办法]
千千静听我没控制过,我以前(很久很久了)控制过winamp(好像是这么拼的吧,也是播放MP3的)。你可以发送虚拟键,发快捷键。
[解决办法]
我也很想知道答案。
帮楼主顶吧!
以下纯猜测想象:
第一要得到控件的ID,因为控件是资源,它是编译时就已经存在的了。
比如 #define IDC_DATA_TXT 1001
1001是在编译时确定的,不是运行时,所以它是固定的。
第二得到控件所在窗体的句柄FindWindow得不到,你可以通过进程名,那个一定是固定的。
第三hText = GetDlgItem(hMyWnd,IDC_DATA_TXT);得到句柄
IDC_DATA_TXT是你第一得到的ID,hMyWnd是第二得到的窗体句柄。
第四有了hText 你可发消息。

我记得有写资源编辑器可以得到第一里提到的ID

纯想象

热点排行