请问如何获取 ListView 的标题栏高度?
这可能有点笨拙,但你可以这样做:
listView.Items[0].Bounds.Top
如果列表中只有一个项目,这个方法才能生效。因此,您可能希望在创建列表时先暂时添加一个项目并保留高度值。
另外,您也可以使用以下方法:
listView.TopItem.Bounds.Top
为了随时进行测试,但仍需要列表中至少有一项。以下是使用Win32 Interop调用获取listview头部高度的方法。
[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;
}
}
@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;
}
}
我已验证此方法适用于我的Win32++应用程序:
CHeader* hdr = GetHeader();
CRect rcHdr = hdr->GetWindowRect();
标题高度是 rcHdr.Height()