对于模拟点击别的软件的下拉框,可以使用Windows API函数来实现。

  1. 找到目标窗口的句柄

使用FindWindow函数可以找到目标窗口的句柄,需要传入窗口的类名和窗口标题。

示例代码:

IntPtr hWnd = FindWindow('窗口类名', '窗口标题');
  1. 找到下拉框控件的句柄

使用FindWindowEx函数可以找到目标窗口内的下拉框控件句柄,需要传入父窗口的句柄和下拉框控件的类名。

示例代码:

IntPtr hComboBox = FindWindowEx(hWnd, IntPtr.Zero, 'ComboBox', null);
  1. 打开下拉框列表

使用SendMessage函数发送CB_SHOWDROPDOWN消息给下拉框控件,即可打开下拉框列表。

示例代码:

const int CB_SHOWDROPDOWN = 0x014F;
SendMessage(hComboBox, CB_SHOWDROPDOWN, IntPtr.Zero, IntPtr.Zero);
  1. 选择下拉框列表项

使用SendMessage函数发送CB_SETCURSEL消息给下拉框控件,即可选择下拉框列表项。

示例代码:

const int CB_SETCURSEL = 0x014E;
SendMessage(hComboBox, CB_SETCURSEL, selectedIndex, IntPtr.Zero);

其中selectedIndex为要选择的列表项的索引,从0开始。

完整代码示例:

[DllImport('user32.dll', SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport('user32.dll', CharSet = CharSet.Auto)]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

[DllImport('user32.dll', CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

const int CB_SHOWDROPDOWN = 0x014F;
const int CB_SETCURSEL = 0x014E;

public void ClickComboBox(string windowClass, string windowTitle, int comboBoxIndex, int selectedIndex)
{
    IntPtr hWnd = FindWindow(windowClass, windowTitle);
    if (hWnd == IntPtr.Zero) return;

    IntPtr hComboBox = FindWindowEx(hWnd, IntPtr.Zero, 'ComboBox', null);
    for (int i = 0; i < comboBoxIndex; i++)
    {
        hComboBox = FindWindowEx(hWnd, hComboBox, 'ComboBox', null);
        if (hComboBox == IntPtr.Zero) return;
    }

    SendMessage(hComboBox, CB_SHOWDROPDOWN, IntPtr.Zero, IntPtr.Zero);
    SendMessage(hComboBox, CB_SETCURSEL, selectedIndex, IntPtr.Zero);
}

调用示例:

ClickComboBox('窗口类名', '窗口标题', 0, 2);

该示例代码中,comboBoxIndex为要操作的下拉框控件在窗口中的索引,从0开始。selectedIndex为要选择的列表项的索引,从0开始。

WinForm 模拟点击其他软件下拉框代码详解

原文地址: https://www.cveoy.top/t/topic/lC10 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录