Visual Studio 2010的HWnd

有没有办法从VSIX扩展中获取到Visual Studio 2010顶部窗口的HWnd指针? (我想改变窗口的标题)。

由于很有可能您的VSIX扩展将在Visual Studio中运行,您应该尝试这样做:

System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle 

(注意如果你这么做太早,你会得到VS Splash屏幕……)

我假设您想在C#中以编程方式执行此操作?

你需要在你的类中定义这个P / Invoke:

 [DllImport("user32.dll")] static extern int SetWindowText(IntPtr hWnd, string text); 

然后有一些看起来类似于以下内容的代码:

 Process visualStudioProcess = null; //Process[] allProcesses = Process.GetProcessesByName("VCSExpress"); // Only do this if you know the exact process name // Grab all of the currently running processes Process[] allProcesses = Process.GetProcesses(); foreach (Process process in allProcesses) { // My process is called "VCSExpress" because I have C# Express, but for as long as I've known, it's been called "devenv". Change this as required if (process.ProcessName.ToLower() == "vcsexpress" || process.ProcessName.ToLower() == "devenv" /* Other possibilities*/) { // We have found the process we were looking for visualStudioProcess = process; break; } } // This is done outside of the loop because I'm assuming you may want to do other things with the process if (visualStudioProcess != null) { SetWindowText(visualStudioProcess.MainWindowHandle, "Hello World"); } 

Doc on Process: http : //msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx

Doc / P / Invoke: http : //msdn.microsoft.com/en-us/library/aa288468%28VS.71%29.aspx

在我的本地尝试这个代码,它似乎设置了窗口标题,但Visual Studio在许多条件下覆盖它:获得焦点,进入/离开调试模式……这可能很麻烦。

注意:您可以直接从Process对象获取窗口标题,但不能设置它。

您可以使用EnvDTE API获取主窗口的HWnd:

 var hwndMainWindow = (IntPtr) dte.MainWindow.HWnd; 

在Visual Studio 2010/2012中,使用WPF实现主窗口和部分用户控件。 您可以立即获取主窗口的WPF窗口并使用它。 我为此写了以下扩展方法:

 public static Window GetWpfMainWindow(this EnvDTE.DTE dte) { if (dte == null) { throw new ArgumentNullException("dte"); } var hwndMainWindow = (IntPtr)dte.MainWindow.HWnd; if (hwndMainWindow == IntPtr.Zero) { throw new NullReferenceException("DTE.MainWindow.HWnd is null."); } var hwndSource = HwndSource.FromHwnd(hwndMainWindow); if (hwndSource == null) { throw new NullReferenceException("HwndSource for DTE.MainWindow is null."); } return (Window) hwndSource.RootVisual; }