在comboBox的items中,如果item内容很长的话,我想让DropDownWidth能够根据item长度来改变。但是我调用了api以后,为什么没有返回值?
[DllImport("gdi32.dll")]
public static extern long GetTextExtentPoint32(System.IntPtr hDC,string lpsz,long cbString,System.Drawing.Size lpSize);
private void button1_Click(object sender, System.EventArgs e)
{
int len=this.comboBox1.Items[0].ToString().Length;
string text=this.comboBox1.Items[0].ToString();
foreach(object o in this.comboBox1.Items)
{
if(o.ToString().Length>len)
{
len=o.ToString().Length; 
text=o.ToString(); 
}
}
  
System.Drawing.Size  s=new System.Drawing.Size(); 
    GetTextExtentPoint32(this.comboBox1.Handle,text,len,s);
this.comboBox1.DropDownWidth=(int)s.Width;  
}

解决方案 »

  1.   

    似乎可以不用API的,试试 System.Drawing.Graphics.MeasureString() 方法。
      

  2.   

    具体可以查看微软出版的C# windows程序设计!
      

  3.   

    SizeF sizef=this.CreateGraphics().MeasureString(comboBox1.Text,comboBox1.Font);
    comboBox1.Width=25+(int)sizef.Width;这段代码可实现楼主的功能,
    楼上在合适的位置放进去吧。
      

  4.   

    System.Drawing.Graphics.MeasureString() 
    上面的方法是。net里专门用来测试字符串长度的
      

  5.   

    怎么都是使用Graphics.MeasureString()来测量的,这种方法是可以的,但是我想其后台还是调用API的,我想问问怎么使用上面的API