有没有办法从 VSIX 扩展中获取指向 Visual Studio 2010 顶部窗口的 HWnd 指针?(我想更改窗口的标题)。
问问题
1735 次
3 回答
3
我假设您想在 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");
}
过程文档:http: //msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx
P/Invoke 文档:http: //msdn.microsoft.com/en-us/library/aa288468%28VS.71%29.aspx
在我的本地尝试此代码,它似乎设置了窗口标题,但 Visual Studio 在许多情况下会覆盖它:获得焦点,进入/离开调试模式......这可能很麻烦。
注意:您可以直接从 Process 对象获取窗口标题,但不能设置它。
于 2010-12-14T16:14:11.640 回答
3
由于您的 VSIX 扩展很有可能在 Visual Studio 的进程内运行,您应该尝试以下操作:
System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle
(请注意,如果您过早执行此操作,您将获得 VS 启动画面 ...)
于 2010-12-14T16:21:14.880 回答
3
您可以使用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;
}
于 2012-12-09T09:41:02.467 回答