2012-02-08 33 views
3

我有从组合框继承的控件(实现C#,.Net 2.0)。它有过滤和其他东西。为了保持用户界面的正确性,当筛选过程中的项目数量下降时,下拉列表将更改其大小以适应剩余项目的数量(由NativeMethods.SetWindowPos(...)完成)。如何检查组合框下拉列表是向上还是向下显示?

是否有任何方法检查下拉列表是否显示上或下(字面上) - 不检查它是否打开,是否打开,但在哪个方向上,向上或向下?

欢呼声,JBK

+0

您还需要GetWindowRect()来找出它在哪里。 – 2012-02-08 12:37:11

+0

是的,我找到了答案,但我需要等待8小时才能发布,因为没有至少100分:)刚刚获取组合和下拉的句柄,从它们中获取矩形,并比较两者。 – jotbek 2012-02-08 12:46:49

回答

1

所以我找到了答案:

在这里,我们有两个手柄,以组合框:

/// <summary> 
    /// Gets a handle to the combobox 
    /// </summary> 
    private IntPtr HwndCombo 
    { 
     get 
     { 
      COMBOBOXINFO pcbi = new COMBOBOXINFO(); 
      pcbi.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(pcbi); 
      NativeMethods.GetComboBoxInfo(this.Handle, ref pcbi); 
      return pcbi.hwndCombo; 
     } 
    } 

而对于下拉列表组合框:

/// <summary> 
    /// Gets a handle to the combo's drop-down list 
    /// </summary> 
    private IntPtr HwndDropDown 
    { 
     get 
     { 
      COMBOBOXINFO pcbi = new COMBOBOXINFO(); 
      pcbi.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(pcbi); 
      NativeMethods.GetComboBoxInfo(this.Handle, ref pcbi); 
      return pcbi.hwndList; 
     } 
    } 

现在,我们可以从手柄得到矩形:

RECT comboBoxRectangle; 
    NativeMethods.GetWindowRect((IntPtr)this.HwndCombo, out comboBoxRectangle); 

// get coordinates of combo's drop down list 
    RECT dropDownListRectangle; 
    NativeMethods.GetWindowRect((IntPtr)this.HwndDropDown, out dropDownListRectangle); 

现在我们可以检查:

if (comboBoxRectangle.Top > dropDownListRectangle.Top) 
    { 
     .... 
    } 
3

组合框有两个事件时,下拉部分打开和关闭被解雇(DropDownDropDownClosed),所以你可能希望处理程序附加到他们监视控制的状态。

另外,还有一个布尔属性(DroppedDown)应该告诉你当前的状态。

+0

是的,但实际上我想知道是否显示下拉菜单(字面意思)。我的意思是我知道何时组合显示,但它可以显示上或下取决于组合框在屏幕上的位置。 – jotbek 2012-02-08 12:19:27

+0

噢,你的意思是下拉列表部分显示在文本字段的上面还是下面? – 2012-02-08 12:30:23

+0

是的,确切地说。 :) – jotbek 2012-02-08 12:40:15

1

组合框向下或向上开放,取决于他们必须打开的空间:如果他们在他们下面有可用空间,他们会像往常一样向下开放,否则他们会向上打开。

所以你只需要检查他们是否有足够的空间在他们下面知道。试试这个代码:

void CmbTestDropDown(object sender, EventArgs e) 
{ 
    Point p = this.PointToScreen(cmbTest.Location); 
    int locationControl = p.Y; // location on the Y axis 
    int screenHeight = Screen.GetBounds(new Point(0,0)).Bottom; // lowest point 
    if ((screenHeight - locationControl) < cmbTest.DropDownHeight) 
     MessageBox.Show("it'll open upwards"); 
    else MessageBox.Show("it'll open downwards"); 
} 
相关问题