问题
Is there a way to get the HWnd pointer to the top window of Visual Studio 2010 from a VSIX extension? (I would like to change the title of the window).
回答1:
Since there are good chances that your VSIX extension will be running in-process with Visual Studio, you should try this:
System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle
(Note if you do this too early, you'll get VS Splash screen ...)
回答2:
I'm assuming you want to do this programatically in C#?
You'll need to define this P/Invoke inside your class:
[DllImport("user32.dll")]
static extern int SetWindowText(IntPtr hWnd, string text);
Then have some code that looks similar to the following:
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 on P/Invoke: http://msdn.microsoft.com/en-us/library/aa288468%28VS.71%29.aspx
Trying this code on my local, it seems to set the window title, but Visual Studio overwrites it under many conditions: gains focus, enters/leaves debug mode... This could be troublesome.
Note: You can GET the window title straight from the Process object, but you can't set it.
回答3:
You can use the EnvDTE API to get the HWnd of main window:
var hwndMainWindow = (IntPtr) dte.MainWindow.HWnd;
In Visual Studio 2010/ 2012, the main window and part of user controls implemented using WPF. You can immediately get the WPF window of main window and work with it. I wrote the following extension method for this:
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;
}
来源:https://stackoverflow.com/questions/4440362/hwnd-of-visual-studio-2010