【发布时间】:2010-10-07 00:53:48
【问题描述】:
谁能告诉我如何获取 ListView 的标题高度。
【问题讨论】:
-
这是 WinForms、WCF 还是 ASP.NET?
谁能告诉我如何获取 ListView 的标题高度。
【问题讨论】:
这可能有点老套,但你可以这样做:
listView.Items[0].Bounds.Top
仅当列表中只有一项时才有效。因此,您可能希望在第一次创建列表时临时添加一个并保留高度值。
否则,您可以随时使用:
listView.TopItem.Bounds.Top
要随时进行测试,但您仍需要列表中的至少一项。
【讨论】:
这是使用 Win32 互操作调用获取列表视图标题高度的方法。
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
const long LVM_FIRST = 0x1000;
const long LVM_GETHEADER = (LVM_FIRST + 31);
[DllImport("user32.dll", EntryPoint="SendMessage")]
private static extern IntPtr SendMessage(IntPtr hwnd, long wMsg, long wParam, long lParam);
[DllImport("user32.dll")]
private static extern bool GetWindowRect(HandleRef hwnd, out RECT lpRect);
RECT rc = new RECT();
IntPtr hwnd = SendMessage(ListView1.Handle, LVM_GETHEADER, 0, 0);
if (hwnd != null)
{
if (GetWindowRect(new HandleRef(null, hwnd), out rc))
{
int headerHeight = rc.Bottom - rc.Top;
}
}
【讨论】:
验证这在我的 Win32++ 应用程序中有效:
CHeader* hdr = GetHeader();
CRect rcHdr = hdr->GetWindowRect();
标题高度为 rcHdr.Height()
【讨论】:
@Phaedrus
..很久以前..但是: PInvokeStackImbalance 被调用
SendMessage 的签名是 (long != Uint32):
LRESULT WINAPI SendMessage(
_In_ HWND hWnd,
_In_ UINT Msg,
_In_ WPARAM wParam,
_In_ LPARAM lParam
)
全部改为:
const UInt32 LVM_FIRST = 0x1000;
const UInt32 LVM_GETHEADER = (LVM_FIRST + 31);
[Serializable, System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool GetWindowRect(System.Runtime.InteropServices.HandleRef hwnd, out RECT lpRect);
int youtFuncToGetHeaderHeight()
{
RECT rc = new RECT();
IntPtr hwnd = SendMessage((IntPtr)this.Handle, LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero);
if (hwnd != null)
{
if (GetWindowRect(new System.Runtime.InteropServices.HandleRef(null, hwnd), out rc))
{
int headerHeight = rc.Bottom - rc.Top;
}
}
return -1;
}
【讨论】:
正确代码:
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
const int LVM_FIRST = 0x1000;
const int LVM_GETHEADER = (LVM_FIRST + 31);
[DllImport("user32.dll", EntryPoint="SendMessage")]
private static extern IntPtr SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool GetWindowRect(HandleRef hwnd, out RECT lpRect);
RECT rc = new RECT();
IntPtr hwnd = SendMessage(ListView1.Handle, LVM_GETHEADER, 0, 0);
if (hwnd != null)
{
if (GetWindowRect(new HandleRef(null, hwnd), out rc))
{
int headerHeight = rc.Bottom - rc.Top;
}
}
【讨论】: