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

有帮助吗?

解决方案

由于您的VSIX扩展名将与Visual Studio进行内部处理,因此您应该尝试以下操作:

System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle

(请注意,如果您执行得太早,您将获得VS Splash屏幕...)

其他提示

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

您需要在课内定义此P/调用:

[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");
}

流程的文档: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx

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

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

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

您可以使用 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;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top