Windows窗体,SendMessage行中的语法错误

问题描述 投票:1回答:1

我正在使用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); 
    }
}
c# winforms winapi pinvoke
1个回答
2
投票

要获得组合框的下拉矩形,您可以这样做:

首先,声明RECT结构:

[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
    public int Left;
    public int Top;
    public int Right;
    public int Bottom;
}

注意:Microsoft文档声明这些字段应该是long,但我测试了它,并且由于一些奇怪的原因SendMessageint在这里回答。

第二,正确的SendMessage声明:对于这种特殊情况,您现在可以使用ref RECT参数。请注意,在您的版本中存在错误:hWnd需要是IntPtrwParam只是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应包含所需的值。

© www.soinside.com 2019 - 2024. All rights reserved.