我正在使用Windows窗体,我正在尝试使用SendMessage来获取ComboBox下拉矩形。但是我似乎无法找到允许代码编译的正确参数组合。
我试过复制我发现的例子,但似乎没有编译。
以下是一些不编译的行示例:
var z1 = SendMessage(hWnd, CB_GETDROPPEDCONTROLRECT, (IntPtr)1, (IntPtr)0); // The best overloaded match has some invalid arguments.
var z2 = SendMessage(hWnd, 0x0152, (IntPtr)1, (IntPtr)0);
var z3 = SendMessage(hWnd, CB_GETDROPPEDCONTROLRECT, 1, 0);
var z4 = SendMessage(hWnd, 0x0152, 1, 0);
提前感谢有任何想法使这项工作的人。
这是我的完整代码:
public partial class Form1 : Form
{
[DllImport("user32.dll")]
public static extern int SendMessage(
int hWnd, // handle to destination window
uint Msg, // message
long wParam, // first message parameter
long lParam // second message parameter
);
public Form1()
{
InitializeComponent();
List<string> itms = new List<string>();
itms.Add("Choice 1");
itms.Add("Choice 2");
itms.Add("Choice 3");
itms.Add("Choice 4");
itms.Add("Choice 5");
this.comboBox1.Items.AddRange(itms.ToArray());
}
private void comboBox1_DropDown(object sender, EventArgs e)
{
const int CB_GETDROPPEDCONTROLRECT = 0x0152;
IntPtr hWnd = comboBox1.Handle;
var z = SendMessage(hWnd, CB_GETDROPPEDCONTROLRECT, (IntPtr)1, (IntPtr)0); // The best overloaded match has some invalid arguments.
var z1 = SendMessage(hWnd, 0x0152, (IntPtr)1, (IntPtr)0);
}
}
要获得组合框的下拉矩形,您可以这样做:
首先,声明RECT
结构:
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
注意:Microsoft文档声明这些字段应该是long
,但我测试了它,并且由于一些奇怪的原因SendMessage
用int
在这里回答。
第二,正确的SendMessage
声明:对于这种特殊情况,您现在可以使用ref RECT
参数。请注意,在您的版本中存在错误:hWnd
需要是IntPtr
而wParam
只是int
而不是long
:
[DllImport("user32.dll")]
public static extern int SendMessage(
IntPtr hWnd, // handle to destination window (combobox in this case)
int Msg, // message
int wParam, // first message parameter
ref RECT lParam // second message parameter
);
三,用法:
RECT rect = default;
int result = SendMessage(comboBox1.Handle, 0x0152, 1, ref rect);
comboBox1
当然是你的ComboBox。如果result
为零,则调用失败,否则成功,rect
应包含所需的值。