C# 调用win api获取chrome浏览器中地址

 

//FindWindow 查找窗口
//FindWindowEx查找子窗口
//EnumWindows列举屏幕上的所有顶层窗口,如果回调函数成功则返回非零,失败则返回零
//GetWindowText返回窗口的标题

一、首先要先导入要使用到的win api

[DllImport("user32.dll")]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("User32.dll")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
static extern int EnumWindows(EnumWindowsProc hWnd, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpText, int nCount);
[DllImport("user32.dll")]
private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, StringBuilder lParam);

private const int WM_GETTEXT = 0x00D;
private static string _url;

 

//定义委托

delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);


static void Main(string[] args)
{ 
string url = GetWindowText();

 Console.WriteLine(url);
Console.ReadKey();

}

public static string GetWindowText()
{

IntPtr chrom = IntPtr.Zero;
EnumWindowsProc enwdproc = new EnumWindowsProc(FindChrom);

if (EnumWindows(enwdproc, IntPtr.Zero) >= 0)
return _url;
else
return null;
}

//回调函数
static bool FindChrom(IntPtr hWnd, IntPtr lParam)
{

var sb = new StringBuilder(256);
GetWindowText(hWnd, sb, sb.Capacity);

if (sb.ToString() != String.Empty)
{
if (hWnd != IntPtr.Zero)
{
IntPtr tb = FindWindowEx(hWnd, new IntPtr(0), "Chrome_OmniboxView", ""); //Chrome_OmniboxView是通过Spy++获得的

StringBuilder strbld = new StringBuilder(2083);
SendMessage(tb, WM_GETTEXT, 2083, strbld);
_url = strbld.ToString();
}
return false;

}
//回调函数有返回值

return true;

}

 

posted @ 2013-07-09 13:12  cindy_Lu  阅读(3846)  评论(1编辑  收藏  举报