c#取外部自绘listview的内容
时间: 2023-09-05 10:15:18 浏览: 101
如果你想获取外部应用程序中自绘 ListView 的内容,你需要使用 Windows API 来完成这个任务。以下是一个 C# 示例代码,演示如何获取另一个应用程序中的 ListView 内容:
```csharp
using System;
using System.Runtime.InteropServices;
using System.Text;
public class NativeMethods
{
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SendMessage(IntPtr hWnd, int wMsg, int wParam, StringBuilder lParam);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
public const int LVM_FIRST = 0x1000;
public const int LVM_GETITEMCOUNT = LVM_FIRST + 4;
public const int LVM_GETITEMTEXT = LVM_FIRST + 45;
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
}
public class ListViewHelper
{
public static int GetItemCount(IntPtr listViewHandle)
{
IntPtr result = NativeMethods.SendMessage(listViewHandle, NativeMethods.LVM_GETITEMCOUNT, IntPtr.Zero, IntPtr.Zero);
return result.ToInt32();
}
public static string GetItemText(IntPtr listViewHandle, int itemIndex, int subItemIndex = 0)
{
StringBuilder sb = new StringBuilder(512);
IntPtr result = NativeMethods.SendMessage(listViewHandle, NativeMethods.LVM_GETITEMTEXT, (IntPtr)itemIndex, sb);
return sb.ToString();
}
}
public class Program
{
public static void Main()
{
string windowTitle = "Window Title";
string listViewClassName = "SysListView32";
IntPtr windowHandle = NativeMethods.FindWindow(null, windowTitle);
IntPtr listViewHandle = NativeMethods.FindWindowEx(windowHandle, IntPtr.Zero, listViewClassName, null);
if (listViewHandle != IntPtr.Zero)
{
int itemCount = ListViewHelper.GetItemCount(listViewHandle);
Console.WriteLine("Item count: {0}", itemCount);
for (int i = 0; i < itemCount; i++)
{
string itemText = ListViewHelper.GetItemText(listViewHandle, i);
Console.WriteLine("Item {0}: {1}", i, itemText);
}
}
}
}
```
在示例代码中,`NativeMethods` 类包含了一些 Windows API 函数的声明。`ListViewHelper` 类提供了两个用于获取 ListView 内容的静态方法。`Main` 方法中,我们首先使用 `FindWindow` 函数查找窗口句柄,然后使用 `FindWindowEx` 函数查找 ListView 句柄。如果找到了 ListView 句柄,我们可以使用 `GetItemCount` 和 `GetItemText` 方法获取 ListView 的项数和项文本。
阅读全文