VSIX 拡張機能から Visual Studio 2010 のトップ ウィンドウへの HWnd ポインターを取得する方法はありますか? (ウィンドウのタイトルを変更したい)。
3 に答える
VSIX 拡張機能が Visual Studio でインプロセスで実行される可能性が高いため、次のことを試してください。
System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle
(早すぎるとVSスプラッシュ画面になってしまうので注意...)
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 オブジェクトから直接取得できますが、設定することはできません。
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;
}