/// <summary> /// Implements the OnConnection method of the IDTExtensibility2 interface. /// Receives notification that the Add-in is being loaded. /// </summary> /// <param name="application">Root object of the host application.</param> /// <param name="connectMode"> /// Describes how the Add-in is being loaded (e.g. command line or UI). This is unused since /// the add-in functions the same regardless of how it was loaded. /// </param> /// <param name="addInInst">Object representing this Add-in.</param> /// <param name="custom">Unused, but could contain host specific data for the add-in.</param> /// <seealso class='IDTExtensibility2' /> public void OnConnection( object application, ext_ConnectMode connectMode, object addInInst, ref Array custom) { dte_ = (DTE2)application; debuggerEvents_ = dte_.Events.DebuggerEvents; debuggerEvents_.OnEnterDesignMode += DebuggerOnEnterDesignMode; debuggerEvents_.OnEnterRunMode += DebuggerOnEnterRunMode; commandEvents_ = dte_.Events.CommandEvents; commandEvents_.AfterExecute += CommandEventsAfterExecute; try { webServerOutputPane_ = dte_.ToolWindows.OutputWindow.OutputWindowPanes.Item( Strings.WebServerOutputWindowTitle); } catch (ArgumentException) { // This exception is expected if the window pane hasn't been created yet. webServerOutputPane_ = dte_.ToolWindows.OutputWindow.OutputWindowPanes.Add( Strings.WebServerOutputWindowTitle); } }
public FindEvents(Plugin plugin) : base("FindEvents", "For debugging") { mPlugin = plugin; mCommandEvents = mPlugin.App.DTE.Events.get_CommandEvents(null, 0); mCommandEvents.BeforeExecute += BeforeCommandExecute; mCommandEvents.AfterExecute += AfterCommandExecute; }
public AddInAdapter(object addInInst) { _addInInstance = (AddIn)addInInst; _applicationObject = (DTE2)_addInInstance.DTE; _CommandEvents = _applicationObject.Events.get_CommandEvents("{52692960-56BC-4989-B5D3-94C47A513E8D}", 1); _CommandEvents.AfterExecute += new _dispCommandEvents_AfterExecuteEventHandler(_CommandEvents_AfterExecute); _CommandEvents.BeforeExecute += new _dispCommandEvents_BeforeExecuteEventHandler(_CommandEvents_BeforeExecute); }
/// <summary>Implements the OnConnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being loaded.</summary> /// <param term='application'>Root object of the host application.</param> /// <param term='connectMode'>Describes how the Add-in is being loaded.</param> /// <param term='addInInst'>Object representing this Add-in.</param> /// <seealso class='IDTExtensibility2' /> public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom) { _applicationObject = (DTE)application; // hook into the Paste Command Command cmd = _applicationObject.Commands.Item("Edit.Paste", 0); events = _applicationObject.Events.get_CommandEvents(cmd.Guid, cmd.ID); events.BeforeExecute += OnPaste; }
protected override void Initialize() { base.Initialize(); var dte = GetService(typeof(SDTE)) as DTE; var debugCommand = dte.Application.Commands.Item(DebugStartCommandName); debugEvents = dte.Application.Events.CommandEvents[debugCommand.Guid, debugCommand.ID]; debugEvents.BeforeExecute += debugEvents_BeforeExecute; StopAndroidLogging(); }
public void AddSubscription() { // "{1496A755-94DE-11D0-8C3F-00C04FC2AAE2}, 1113" Guid-ID pair refer to // Project.AddReference command. // About how to get the Guid and ID of the specific command, please take a // look at this link on Dr.eX's blog: // http://blogs.msdn.com/dr._ex/archive/2007/04/17/using-enablevsiplogging- // to-identify-menus-and-commands-with-vs-2005-sp1.aspx try { _breakpointsEvents = _applicationObject.Events.get_CommandEvents( "{5EFC7975-14BC-11CF-9B2B-00AA00573819}", 769); _breakpointsEvents.BeforeExecute += new _dispCommandEvents_BeforeExecuteEventHandler(breakpointsEvents_BeforeExecute); __findAllReferencesEvents = _applicationObject.Events.get_CommandEvents( "{5EFC7975-14BC-11CF-9B2B-00AA00573819}", 1915); __findAllReferencesEvents.BeforeExecute += new _dispCommandEvents_BeforeExecuteEventHandler(findAllReferencesEvents_BeforeExecute); _gotoDefinitionEvents = _applicationObject.Events.get_CommandEvents( "{5EFC7975-14BC-11CF-9B2B-00AA00573819}", 935); _gotoDefinitionEvents.BeforeExecute += new _dispCommandEvents_BeforeExecuteEventHandler(gotoDefinitionEvents_BeforeExecute); _stopEvents = _applicationObject.Events.get_CommandEvents( "{5EFC7975-14BC-11CF-9B2B-00AA00573819}", 179); _stopEvents.BeforeExecute += new _dispCommandEvents_BeforeExecuteEventHandler(stopEvents_BeforeExecute); _startEvents = _applicationObject.Events.get_CommandEvents( "{5EFC7975-14BC-11CF-9B2B-00AA00573819}", 295); _startEvents.BeforeExecute += new _dispCommandEvents_BeforeExecuteEventHandler(startEvents_BeforeExecute); _debuggerEvents = _applicationObject.Events.DebuggerEvents; _debuggerEvents.OnEnterBreakMode += new _dispDebuggerEvents_OnEnterBreakModeEventHandler(debuggerEvents_OnEnterBreakMode); } catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.Message); } }
protected override void Initialize() { base.Initialize(); DTE dte = (DTE)GetService(typeof(DTE)); _CommandEvents = dte.Events.CommandEvents; _PropertyInsertTabs = dte.Properties["TextEditor", "CSharp"].Item("InsertTabs"); _CommandEvents.BeforeExecute += Command_BeforeExecute; _CommandEvents.AfterExecute += Command_AfterExecute; }
public override bool RegisterEventForMonitoring(object dte) { if (!isDisposed && eventTypeObject == null && dte != null) { eventTypeObject = (dte as DTE).Events.get_CommandEvents(Guid, EventID) as CommandEvents; } if (eventTypeObject != null) { eventTypeObject.AfterExecute += new _dispCommandEvents_AfterExecuteEventHandler(OnAfterExecute); } return (eventTypeObject != null); }
/// <summary> /// Initializes a new instance of the <see cref="CommandManager"/> class. /// </summary> public CommandManager( IServiceProvider serviceProvider, IEnumerable<Lazy<ICommandExtension, CommandAttribute>> allCommands, IEnumerable<Lazy<ICommandFilter, CommandFilterAttribute>> allFilters, IEnumerable<Lazy<ICommandInterceptor, CommandInterceptorAttribute>> allInterceptors) { this.serviceProvider = serviceProvider; this.vsShell = serviceProvider.GetService<SVsShell, IVsShell>(); this.commandEvents = serviceProvider.GetService<DTE>().Events.CommandEvents; this.commands = allCommands; this.filters = allFilters; this.interceptors = allInterceptors.ToList(); this.commandEvents.BeforeExecute += OnBeforeExecute; this.commandEvents.AfterExecute += OnAfterExecute; }
public BuildOnSave(Package package) { IServiceProvider serviceProvider = package; _dte = serviceProvider.GetService(typeof(DTE)) as DTE; _events = _dte.Events; _documentEvents = _events.DocumentEvents; _buildEvents = _events.BuildEvents; var guid = typeof(VSConstants.VSStd97CmdID).GUID.ToString("B"); _buildSolutionEvent = _dte.Events.CommandEvents[guid, (int)VSConstants.VSStd97CmdID.BuildSln]; var commandService = serviceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService; _topMenu = new MenuCommand(delegate { }, new CommandID(CommandSet, TopMenuCommandId)); _menuItem = new MenuCommand(enableDisableBuildOnSave, new CommandID(CommandSet, CommandId)); _buildTypeSolution = new MenuCommand(setBuildTypeToSolution, new CommandID(CommandSet, BuildTypeSolutionCommandId)); _buildTypeStartupProject = new MenuCommand(setBuildTypeToStartupProject, new CommandID(CommandSet, BuildTypeStartupProjectCommandId)); _buildTypeProjectsOfSavedFiles = new MenuCommand(setBuildTypeToProjectsOfSavedFiles, new CommandID(CommandSet, BuildTypeProjectsOfSavedFilesCommandId)); _buildTypeAffectedProjectsOfSavedFiles = new MenuCommand(setBuildTypeToAffectedProjectsOfSavedFiels, new CommandID(CommandSet, BuildTypeAffectedProjectsOfSavedFilesCommandId)); commandService.AddCommand(_topMenu); commandService.AddCommand(_menuItem); commandService.AddCommand(_buildTypeSolution); commandService.AddCommand(_buildTypeStartupProject); commandService.AddCommand(_buildTypeProjectsOfSavedFiles); commandService.AddCommand(_buildTypeAffectedProjectsOfSavedFiles); // create the output pane. _outputWindow = _dte.Windows.Item(Constants.vsWindowKindOutput); _outputPane = ((OutputWindow)_outputWindow.Object).OutputWindowPanes.Add("BuildOnSave"); _topMenu.Visible = true; _solutionOptions = DefaultOptions; Log.I("BuildOnSave initialized"); syncOptions(); }
protected override void Initialize() { /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. Trace.WriteLine(String.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", ToString())); base.Initialize(); this.dte = GetService(typeof (DTE)) as DTE; if (this.dte == null) { throw new NullReferenceException("DTE is null"); } this.uiShell = GetService(typeof (IVsUIShell)) as IVsUIShell; // Initialize command events listeners this.events = this.dte.Events; // File.SaveSelectedItems command this.fileSaveSelectedItems = this.events.CommandEvents["{5EFC7975-14BC-11CF-9B2B-00AA00573819}", 331]; this.fileSaveSelectedItems.BeforeExecute += this.OnFileSaveSelectedItemsBeforeExecute; // File.SaveAll command this.fileSaveAll = this.events.CommandEvents["{5EFC7975-14BC-11CF-9B2B-00AA00573819}", 224]; this.fileSaveAll.BeforeExecute += this.OnFileSaveAllBeforeExecute; //Initialize menu command // Add our command handlers for menu (commands must exist in the .vsct file) var menuCommandService = this.GetService(typeof (IMenuCommandService)) as OleMenuCommandService; if (menuCommandService != null) { // Create the command for the menu item. var menuCommandId = new CommandID(GuidList.XamlMagicPackageCommandSet, (int) PkgCmdIDList.FormatXamlCommand); var menuItem = new MenuCommand(this.MenuItemCallback, menuCommandId); menuCommandService.AddCommand(menuItem); } }
public CommandController(DTE dte, Func<EventHandler, MenuCommand> initBreakOnAllCommand, IVsMonitorSelection monitorSelection, ExceptionBreakManager breakManager, IDiagnosticLogger logger) { _monitorSelection = monitorSelection; _breakManager = breakManager; _logger = logger; _breakOnAllCommand = initBreakOnAllCommand(breakOnAllCommand_Callback); _requiredUiContextCookies = new HashSet<uint>(RequiredUIContexts.Select(ConvertToUIContextCookie)); UpdateCommandAvailability(); _selectionEventsCookie = SubscribeToSelectionEvents(); UpdateCommandCheckedState(); _breakManager.CurrentStateChanged += breakManager_CurrentStateChanged; _debugExceptionsEvents = SubscribeToDebugExceptionsCommand(dte); }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initilaization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", ToString())); base.Initialize(); _dte = GetService(typeof (DTE)) as DTE; if (_dte == null) { throw new NullReferenceException("DTE is null"); } _uiShell = GetService(typeof (IVsUIShell)) as IVsUIShell; // Initialize command events listeners _events = _dte.Events; // File.SaveSelectedItems command _fileSaveSelectedItems = _events.CommandEvents["{5EFC7975-14BC-11CF-9B2B-00AA00573819}", 331]; _fileSaveSelectedItems.BeforeExecute += OnFileSaveSelectedItemsBeforeExecute; // File.SaveAll command _fileSaveAll = _events.CommandEvents["{5EFC7975-14BC-11CF-9B2B-00AA00573819}", 224]; _fileSaveAll.BeforeExecute += OnFileSaveAllBeforeExecute; //Initialize menu command // Add our command handlers for menu (commands must exist in the .vsct file) var menuCommandService = GetService(typeof (IMenuCommandService)) as OleMenuCommandService; if (null != menuCommandService) { // Create the command for the menu item. var menuCommandId = new CommandID(GuidList.guidXamlStyler_PackageCmdSet, (int) PkgCmdIDList.cmdidBeautifyXaml); var menuItem = new MenuCommand(MenuItemCallback, menuCommandId); menuCommandService.AddCommand(menuItem); } }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { base.Initialize(); mRunningDocTableEvents = new RunningDocTableEvents(this); //Settings command is always visible mSettingsCmd = new SettingsCommand(this, CommandSet, CommandIds.kSettingsId); var dte = GetService(typeof(DTE)) as DTE2; mBuildEvents = dte.Events.BuildEvents; mCommandEvents = dte.Events.CommandEvents; var generalOptions = (ClangGeneralOptionsView)this.GetDialogPage(typeof(ClangGeneralOptionsView)); if (null == generalOptions.Version || string.IsNullOrWhiteSpace(generalOptions.Version)) { ShowToolbare(dte); // Show the toolbar on the first install } AdviseSolutionEvents(); }
public BuildOnSave(DTE dte, OleMenuCommandService commandService) { _dte = dte; _events = _dte.Events; _documentEvents = _events.DocumentEvents; _buildEvents = _events.BuildEvents; var guid = typeof(VSConstants.VSStd97CmdID).GUID.ToString("B"); _buildSolutionEvent = _dte.Events.CommandEvents[guid, (int)VSConstants.VSStd97CmdID.BuildSln]; _topMenu = new MenuCommand(delegate { }, new CommandID(CommandSet, TopMenuCommandId)); _menuItem = new MenuCommand(enableDisableBuildOnSave, new CommandID(CommandSet, CommandId)); _buildTypeSolution = new MenuCommand(setBuildTypeToSolution, new CommandID(CommandSet, BuildTypeSolutionCommandId)); _buildTypeStartupProject = new MenuCommand(setBuildTypeToStartupProject, new CommandID(CommandSet, BuildTypeStartupProjectCommandId)); commandService.AddCommand(_topMenu); commandService.AddCommand(_menuItem); commandService.AddCommand(_buildTypeSolution); commandService.AddCommand(_buildTypeStartupProject); // create the output pane. _outputWindow = _dte.Windows.Item(Constants.vsWindowKindOutput); _outputPane = ((OutputWindow)_outputWindow.Object).OutputWindowPanes.Add("BuildOnSave"); _topMenu.Visible = true; _solutionOptions = DefaultOptions; Log.I("BuildOnSave initialized"); syncOptions(); }
/// <summary> /// Initializes a new instance of the <see cref="ToolWindow1Control"/> class. /// </summary> public ToolWindow1Control() { this.InitializeComponent(); this.DataContext = this.parser; this.dte = Global.GetDTE2(); commandEvents = dte.Events.CommandEvents; commandEvents.AfterExecute += CommandEvents_AfterExecute; watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName; watcher.Changed += Watcher_Changed; watcher.Created += Watcher_Changed; watcher.Deleted += Watcher_Changed; watcher.Renamed += Watcher_Changed; foreach (var itemName in typeof(FontWeights).GetProperties().Select(x => x.Name)) { fontWeights.Items.Add(itemName); if (fontWeights.SelectedItem == null && codeMapList.FontWeight.ToString() == itemName) { fontWeights.SelectedItem = itemName; } } foreach (var itemName in Fonts.SystemFontFamilies.Select(x => x.ToString()).OrderBy(x => x)) { fonts.Items.Add(itemName); if (fonts.SelectedItem == null && codeMapList.FontFamily.ToString() == itemName) { fonts.SelectedItem = itemName; } } ReadSettings(); initialized = true; }
private CommandHandler(IServiceProvider provider, Options options) { _options = options; _dte = (DTE2)provider.GetService(typeof(DTE)); _control = new StatusbarControl(options, _dte); _events = _dte.Events.CommandEvents; _events.AfterExecute += AfterExecute; _events.BeforeExecute += BeforeExecute; var injector = new StatusBarInjector(Application.Current.MainWindow); injector.InjectControl(_control); _timer = new Timer(); _timer.Elapsed += (s, e) => { _timer.Stop(); _control.SetVisibility(Visibility.Collapsed); }; _options.Saved += (s, e) => { SetTimeout(); if (!_options.LogToStatusBar) { _control.SetVisibility(Visibility.Collapsed); } if (!_options.LogToOutputWindow) { Logger.DeletePane(); } }; SetTimeout(); }
public Project(Func <EnvDTE.Project> vsProjectFuncFunc) { _vsProjectFunc = vsProjectFuncFunc; _dte = Package.GetGlobalService(typeof(DTE)) as DTE; if (_events2 != null) { return; } _events2 = _dte.Events as Events2; _codeModelEvents = _events2.CodeModelEvents; _commandEvents = _events2.CommandEvents; _projectItemsEvents = _events2.ProjectItemsEvents; _documentEvents = _events2.DocumentEvents; _documentEvents.DocumentSaved += document => { if (document.IsGaugeConceptFile()) { RefreshImplementations(); } }; _projectItemsEvents.ItemAdded += projectItem => RefreshImplementations(); _projectItemsEvents.ItemRemoved += projectItem => RefreshImplementations(); _projectItemsEvents.ItemRenamed += (item, name) => RefreshImplementations(); _codeModelEvents.ElementAdded += element => RefreshImplementations(); _codeModelEvents.ElementChanged += (element, change) => RefreshImplementations(); _codeModelEvents.ElementDeleted += (parent, element) => RefreshImplementations(); _commandEvents.AfterExecute += (cmdId, id, customIn, customOut) => { if ((VSConstants.VSStd2KCmdID)id == VSConstants.VSStd2KCmdID.RENAME) { RefreshImplementations(); } }; }
public SolutionViewModel(SolutionStateMachine slnMachine, WorkspaceStateMachine wsMachine, Action <string> writeLog, ISender <IRingCommand> commandQueue) { ThreadHelper.ThrowIfNotOnUIThread(); _writeLog = writeLog; _commandQueue = commandQueue; _wsMachine = wsMachine; _slnMachine = slnMachine; Configure(_slnMachine); var debugStartCmd = Dte.Commands.Item("Debug.Start"); _solutionEventsHandler = new SolutionsEventsHandler(Sln); _debuggerEventsHandler = new DebuggerEventsHandler(Debugger); _projStartDebugEvent = Dte.Events.CommandEvents["{" + VSConstants.VSStd2K + "}", (int)VSConstants.VSStd2KCmdID.PROJSTARTDEBUG]; _projStepIntoEvent = Dte.Events.CommandEvents["{" + VSConstants.VSStd2K + "}", (int)VSConstants.VSStd2KCmdID.PROJSTEPINTO]; _debugStartEvent = Dte.Events.CommandEvents[debugStartCmd.Guid, debugStartCmd.ID]; _debuggerEvents = Dte.Events.DebuggerEvents; _buildEvents = Dte.Events.BuildEvents; _buildEvents.OnBuildBegin += BuildBegin; _buildEvents.OnBuildDone += BuildDone; _buildEvents.OnBuildProjConfigBegin += ProjectBuildBegin; _buildEvents.OnBuildProjConfigDone += ProjectBuildDone; _projStepIntoEvent.BeforeExecute += DebugProjectsAdd; _projStartDebugEvent.BeforeExecute += DebugProjectsAdd; _debugStartEvent.BeforeExecute += DebugStart; _debuggerEvents.OnEnterDesignMode += DebugStop; _solutionEventsHandler.OnAfterOpen += Load; _solutionEventsHandler.OnAfterClose += Unload; _debuggerEventsHandler.OnProcessCreated += DebugProcessAdd; _debuggerEventsHandler.OnProcessRemoved += DebugRemove; _projectProcesses = new ProjectsProcesses(writeLog); //TODO: handle debug detach (probably kill detached the process - figure out how to get it - potentially get PID on creation) //TODO: handle clean up - what should happen if a project or whole solution is cleaned up? Should ring run in a degraded state (With "big exclamation marks" in the window) }
public void Initialize() { if (!initialized) { // Setup solution related stuff this.solutionService = package.GetService <SVsSolution, IVsSolution2>(); this.solutionBuildService = package.GetService <SVsSolutionBuildManager, IVsSolutionBuildManager2>(); this.selectionMonitor = package.GetService <SVsShellMonitorSelection, IVsMonitorSelection>(); // Set startup project ErrorHandler.ThrowOnFailure(this.solutionService.AdviseSolutionEvents(this, out solutionEventsCookie)); ErrorHandler.ThrowOnFailure(this.selectionMonitor.AdviseSelectionEvents(this, out selectionEventsCookie)); ErrorHandler.ThrowOnFailure(this.solutionBuildService.AdviseUpdateSolutionEvents(this, out updateSolutionEventsCookie)); commandEvents = this.appObject.Events.CommandEvents; commandEvents.BeforeExecute += CommandEventsOnBeforeExecute; if (IsSolutionOpen) { foreach (var pHierarchy in GetSupportedProjects()) { var project = ProjectForHierarchy(pHierarchy); Guid projectGuid = pHierarchy.GetGuid(); string projectPath = project.FullName; string projectName = project.UniqueName; ProjectStateMap[projectGuid] = new ProjectState { FilePath = projectPath, UniqueName = projectName, IsLoaded = true }; } } initialized = true; } }
public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom) { _applicationObject = (DTE2)application; _addInInstance = (AddIn)addInInst; //SET THE MEMBER VARIABLES //_debuggerEvents = _applicationObject.Events.DebuggerEvents; //_debuggerEvents.OnEnterBreakMode += new _dispDebuggerEvents_OnEnterBreakModeEventHandler(BreakHandler); //var watchWindow = _applicationObject.Windows.Item(EnvDTE.Constants.vsWindowKindWatch); _objCommandEvents = _applicationObject.Events.CommandEvents; _objCommandEvents.BeforeExecute += new _dispCommandEvents_BeforeExecuteEventHandler(BeforeExecute); if(connectMode == ext_ConnectMode.ext_cm_UISetup) { object []contextGUIDS = new object[] { }; Commands2 commands = (Commands2)_applicationObject.Commands; string toolsMenuName = "Tools"; Microsoft.VisualStudio.CommandBars.CommandBar menuBarCommandBar = ((Microsoft.VisualStudio.CommandBars.CommandBars)_applicationObject.CommandBars)["MenuBar"]; ar: CommandBarControl toolsControl = menuBarCommandBar.Controls[toolsMenuName]; CommandBarPopup toolsPopup = (CommandBarPopup)toolsControl; try { Command command = commands.AddNamedCommand2(_addInInstance, "AddinMultiLineWatch", "AddinMultiLineWatch", "Executes the command for AddinMultiLineWatch", true, 59, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported+(int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); if((command != null) && (toolsPopup != null)) { command.AddControl(toolsPopup.CommandBar, 1); } } catch(System.ArgumentException) { } } }
public BuildContext(IPackageContext packageContext, ControlViewModel viewModel) { _viewModel = viewModel; BuildedProjects = new BuildedProjectsCollection(); BuildingProjects = new List <ProjectItem>(); _buildingProjectsLockObject = ((ICollection)BuildingProjects).SyncRoot; _packageContext = packageContext; Events dteEvents = packageContext.GetDTE().Events; _buildEvents = dteEvents.BuildEvents; _windowEvents = dteEvents.WindowEvents; _commandEvents = dteEvents.CommandEvents; _buildEvents.OnBuildBegin += BuildEvents_OnBuildBegin; _buildEvents.OnBuildDone += (s, e) => BuildEvents_OnBuildDone(); _buildEvents.OnBuildProjConfigBegin += BuildEvents_OnBuildProjectBegin; _buildEvents.OnBuildProjConfigDone += BuildEvents_OnBuildProjectDone; _windowEvents.WindowActivated += WindowEvents_WindowActivated; _commandEvents.AfterExecute += CommandEvents_AfterExecute; }
public IEvent GetEvent(string name) { if (CommandEvents.ContainsKey(name)) { return(CommandEvents[name]); } if (MentionEvents.ContainsKey(name)) { return(MentionEvents[name]); } if (ContinuousEvents.ContainsKey(name)) { return(ContinuousEvents[name]); } if (JoinServerEvents.ContainsKey(name)) { return(JoinServerEvents[name]); } if (LeaveServerEvents.ContainsKey(name)) { return(LeaveServerEvents[name]); } return(null); }
protected override void Initialize() //async System.Threading.Tasks.Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) { base.Initialize(); // TODO : Can remove? VsProjectHelper.Initialize(); //await PrepareWindowsAsync(); PrepareWidnows(); VsEvents.Initialize(this as IVsEventsHandler, GetService(typeof(SVsSolution)) as IVsSolution); DeviceManager.Initialize(VsPackage.outputPaneTizen); DeviceManager.ResetDeviceMonitorRetry(); DeviceManager.StartDeviceMonitor(); TizenPackageTracer.Initialize(); PrepareToolsWindows(); StartDebuggerMonitoring(); base.RegisterEditorFactory(new ManifestEditorFactory(this)); APICheckerCommand.Initialize(this, VsPackage.outputPaneTizen); string guidVSstd97 = "{5efc7975-14bc-11cf-9b2b-00aa00573819}".ToUpper(); int cmdidStartupPrj = 246; DTE2 dte2 = GetService(typeof(SDTE)) as DTE2; CEvents = dte2.Events.CommandEvents[guidVSstd97, cmdidStartupPrj]; CEvents.AfterExecute += SetStartup_AfterExecute; ProfilerPlugin.Initialize(this, outputPaneTizen, dialogFactory); instance = this; }
public AddInEventHandler(DTE _dte) { simpleThreadMessenger = new SimpleThreadMessenger(this); dte = _dte; Events2 events = dte.Events as Events2; buildEvents = (EnvDTE.BuildEvents)events.BuildEvents; buildEvents.OnBuildBegin += new _dispBuildEvents_OnBuildBeginEventHandler(buildEvents_OnBuildBegin); buildEvents.OnBuildProjConfigBegin += new _dispBuildEvents_OnBuildProjConfigBeginEventHandler(this.OnBuildProjConfigBegin); buildEvents.OnBuildDone += new _dispBuildEvents_OnBuildDoneEventHandler(this.buildEvents_OnBuildDone); documentEvents = (EnvDTE.DocumentEvents)events.get_DocumentEvents(null); documentEvents.DocumentSaved += new _dispDocumentEvents_DocumentSavedEventHandler(this.DocumentSaved); projectItemsEvents = (ProjectItemsEvents)events.ProjectItemsEvents; projectItemsEvents.ItemAdded += new _dispProjectItemsEvents_ItemAddedEventHandler(this.ProjectItemsEvents_ItemAdded); projectItemsEvents.ItemRemoved += new _dispProjectItemsEvents_ItemRemovedEventHandler(this.ProjectItemsEvents_ItemRemoved); projectItemsEvents.ItemRenamed += new _dispProjectItemsEvents_ItemRenamedEventHandler(this.ProjectItemsEvents_ItemRenamed); solutionEvents = (SolutionEvents)events.SolutionEvents; solutionEvents.ProjectAdded += new _dispSolutionEvents_ProjectAddedEventHandler(this.SolutionEvents_ProjectAdded); solutionEvents.ProjectRemoved += new _dispSolutionEvents_ProjectRemovedEventHandler(this.SolutionEvents_ProjectRemoved); solutionEvents.Opened += new _dispSolutionEvents_OpenedEventHandler(SolutionEvents_Opened); solutionEvents.AfterClosing += new _dispSolutionEvents_AfterClosingEventHandler(SolutionEvents_AfterClosing); const string debugCommandsGUID = "{5EFC7975-14BC-11CF-9B2B-00AA00573819}"; debugStartEvents = events.get_CommandEvents(debugCommandsGUID, 295); debugStartEvents.BeforeExecute += new _dispCommandEvents_BeforeExecuteEventHandler(debugStartEvents_BeforeExecute); debugStartWithoutDebuggingEvents = events.get_CommandEvents(debugCommandsGUID, 368); debugStartWithoutDebuggingEvents.BeforeExecute += new _dispCommandEvents_BeforeExecuteEventHandler(debugStartWithoutDebuggingEvents_BeforeExecute); dispId_VCFileConfiguration_ExcludedFromBuild = GetPropertyDispId(typeof(VCFileConfiguration), "ExcludedFromBuild"); dispId_VCCLCompilerTool_UsePrecompiledHeader = GetPropertyDispId(typeof(VCCLCompilerTool), "UsePrecompiledHeader"); dispId_VCCLCompilerTool_PrecompiledHeaderThrough = GetPropertyDispId(typeof(VCCLCompilerTool), "PrecompiledHeaderThrough"); dispId_VCCLCompilerTool_PreprocessorDefinitions = GetPropertyDispId(typeof(VCCLCompilerTool), "PreprocessorDefinitions"); dispId_VCCLCompilerTool_AdditionalIncludeDirectories = GetPropertyDispId(typeof(VCCLCompilerTool), "AdditionalIncludeDirectories"); RegisterVCProjectEngineEvents(); if (Connect.Instance().AppWrapperPath == null) { Messages.DisplayCriticalErrorMessage("QtAppWrapper can't be found in the installation directory."); } else { appWrapperProcess = new System.Diagnostics.Process(); appWrapperProcess.StartInfo.FileName = Connect.Instance().AppWrapperPath; } appWrapperThread = new System.Threading.Thread(new System.Threading.ThreadStart(ListenForRequests)); appWrapperThread.Name = "QtAppWrapperListener"; appWrapperThread.Start(); }
public EventHandlerBase(IServiceProvider serviceProvider, IEventGenerator osbideEvents) { if (serviceProvider == null) { throw new Exception("Service provider is null"); } ServiceProvider = serviceProvider; //attach osbide requests _osbideEvents = osbideEvents; _osbideEvents.SolutionSubmitRequest += SolutionSubmitted; _osbideEvents.SubmitEventRequested += SubmitEventRequested; //save references to dte events buildEvents = Dte.Events.BuildEvents; genericCommandEvents = Dte.Events.CommandEvents; menuCommandEvents = Dte.Events.CommandEvents[MenuEventGuid]; debuggerEvents = Dte.Events.DebuggerEvents; documentEvents = Dte.Events.DocumentEvents; findEvents = Dte.Events.FindEvents; miscFileEvents = Dte.Events.MiscFilesEvents; outputWindowEvents = Dte.Events.OutputWindowEvents; selectionEvents = Dte.Events.SelectionEvents; solutionEvents = Dte.Events.SolutionEvents; solutionItemsEvents = Dte.Events.SolutionItemsEvents; textEditorEvents = Dte.Events.TextEditorEvents; //attach osbide requests //var osbideEventGenerator = osbideEvents; //osbideEventGenerator.SolutionSubmitRequest += SolutionSubmitted; //osbideEventGenerator.SubmitEventRequested += SubmitEventRequested; //attach listeners for dte events //build events buildEvents.OnBuildBegin += OnBuildBegin; buildEvents.OnBuildDone += OnBuildDone; //generic command events genericCommandEvents.AfterExecute += GenericCommand_AfterCommandExecute; genericCommandEvents.BeforeExecute += GenericCommand_BeforeCommandExecute; //menu-related command command menuCommandEvents.AfterExecute += MenuCommand_AfterExecute; menuCommandEvents.BeforeExecute += MenuCommand_BeforeExecute; //debugger events debuggerEvents.OnContextChanged += OnContextChanged; debuggerEvents.OnEnterBreakMode += OnEnterBreakMode; debuggerEvents.OnEnterDesignMode += OnEnterDesignMode; debuggerEvents.OnEnterRunMode += OnEnterRunMode; debuggerEvents.OnExceptionNotHandled += OnExceptionNotHandled; debuggerEvents.OnExceptionThrown += OnExceptionThrown; //document events documentEvents.DocumentClosing += DocumentClosing; documentEvents.DocumentOpened += DocumentOpened; documentEvents.DocumentSaved += DocumentSaved; //find events findEvents.FindDone += FindDone; //misc file events miscFileEvents.ItemAdded += ProjectItemAdded; miscFileEvents.ItemRemoved += ProjectItemRemoved; miscFileEvents.ItemRenamed += ProjectItemRenamed; //output window events outputWindowEvents.PaneUpdated += OutputPaneUpdated; //selection events selectionEvents.OnChange += SelectionChange; //solution events solutionEvents.BeforeClosing += SolutionBeforeClosing; solutionEvents.Opened += SolutionOpened; solutionEvents.ProjectAdded += ProjectAdded; solutionEvents.Renamed += SolutionRenamed; //solution item events solutionItemsEvents.ItemAdded += SolutionItemAdded; solutionItemsEvents.ItemRemoved += SolutionItemRemoved; solutionItemsEvents.ItemRenamed += SolutionItemRenamed; //text editor events textEditorEvents.LineChanged += EditorLineChanged; // Create an event log watcher that will notify us if any windows event logs // of type Error are created in the "Application" log file. This is so we can // tell if a user experiences a runtime exception while running their code // outside debug mode. string queryStr = "*[System/Level=2]"; EventLogQuery query = new EventLogQuery("Application", PathType.LogName, queryStr); eventLogWatcher = new EventLogWatcher(query); // subscribe to it's event (Note: it is not enabled yet, it will be enabled if the // user runs without debuging) eventLogWatcher.EventRecordWritten += NETErrorEventRecordWritten; }
void IDTExtensibility2.OnConnection( object oApplication, Extensibility.ext_ConnectMode cmConnectMode, object oAddInInstance, ref System.Array arrCustom ) { _pApplication = ( _DTE )oApplication; _pAddInInstance = ( EnvDTE.AddIn )oAddInInstance; _pf = new ProfilerForm(); _pf.Owner = null; _pf.Closed += new EventHandler(_pf_Closed); // Hook up to run events Command cmdDebug; cmdDebug = _pApplication.Commands.Item( "Debug.Start", 1 ); _cmdevDebugStart = _pApplication.Events.get_CommandEvents( cmdDebug.Guid, cmdDebug.ID ); _cmdevDebugStart.BeforeExecute += new EnvDTE._dispCommandEvents_BeforeExecuteEventHandler( OnBeforeRun ); _cmdevDebugStart.AfterExecute += new EnvDTE._dispCommandEvents_AfterExecuteEventHandler( OnAfterRun ); cmdDebug = _pApplication.Commands.Item( "Debug.StartWithoutDebugging", 1 ); _cmdevNoDebugStart = _pApplication.Events.get_CommandEvents( cmdDebug.Guid, cmdDebug.ID ); _cmdevNoDebugStart.BeforeExecute += new EnvDTE._dispCommandEvents_BeforeExecuteEventHandler( OnBeforeRun ); _cmdevNoDebugStart.AfterExecute += new EnvDTE._dispCommandEvents_AfterExecuteEventHandler( OnAfterRun ); if ( cmConnectMode == Extensibility.ext_ConnectMode.ext_cm_UISetup ) { object[] contextGUIDS = new object[] { }; foreach ( Command cmd in _pApplication.Commands ) { try { if ( cmd.Name != null && cmd.Name.StartsWith( "NProf.Connect" ) ) cmd.Delete(); } catch ( Exception ) { } } try { CommandBar barNProf = _pApplication.CommandBars[ "nprof Profiling" ]; if ( barNProf != null ) barNProf.Delete(); } catch ( Exception ) { } Command command = _pApplication.Commands.AddNamedCommand( _pAddInInstance, "Enable", "Enable nprof", "Toggle nprof integration", true, 0, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusUnsupported ); CommandBar barTools = ( CommandBar )_pApplication.CommandBars[ "Tools" ]; CommandBar barMenu = ( CommandBar )_pApplication.Commands.AddCommandBar( "nprof Profiling", vsCommandBarType.vsCommandBarTypeMenu, barTools, 1 ); CommandBarControl cbc = command.AddControl( barMenu, 1 ); } }
public static void InitializeListeners() { _dte = ServiceProvider.GlobalProvider.GetService(typeof (DTE)) as DTE2; //register for F5 hit event and start previewing if selected document is jsreport _debugCommandEvent = _dte.Events.CommandEvents["{5EFC7975-14BC-11CF-9B2B-00AA00573819}", 295]; _debugCommandEvent.BeforeExecute += (string guid, int id, object @in, object @out, ref bool @default) => { if (_dte.ActiveDocument != null && _dte.ActiveDocument.FullName.Contains(".jsrep") && !_dte.ActiveDocument.FullName.Contains(".png") && !_dte.ActiveDocument.FullName.Contains(".json")) { @default = true; DoPreviewActiveItem().Wait(); } }; //new project item should clear schemas cache, so new jsrep.json is visible in combo _cteateProjectItemEvent = _dte.Events.CommandEvents["{5EFC7975-14BC-11CF-9B2B-00AA00573819}", 220]; _cteateProjectItemEvent.AfterExecute += (string guid, int id, object @in, object @out) => { ReportingServerManagerAdapter.ClearCache(); foreach (Window window in _dte.Windows) { var jsrepEditorPane = window.Object as JsRepEditorPane; if (jsrepEditorPane != null) jsrepEditorPane.MarkRerfeshRequired(); } }; //saving ReportingStartup.cs should restart current server manager _documentEvents = _dte.Events.DocumentEvents; _documentEvents.DocumentSaved += async document => { if (document.FullName.ToLower().Contains("reportingstartup")) { lock (_locker) { if (_configReloadInProgress) return; _configReloadInProgress = true; } try { Trace.TraceInformation("Reloading because of reportingstartup"); await ReportingServerManagerAdapter.StopAsync(); foreach (Window window in _dte.Windows) { var jsrepEditorPane = window.Object as JsRepEditorPane; if (jsrepEditorPane != null) jsrepEditorPane.MarkRerfeshRequired(); } } finally { _configReloadInProgress = false; Trace.TraceInformation("Reloading done"); } } }; ReportingServerManagerAdapter = new ReportingServerManagerAdapter(_dte); }
public EventHandlerBase(IServiceProvider serviceProvider, IOsbideEventGenerator osbideEvents) { if (serviceProvider == null) { throw new Exception("Service provider is null"); } ServiceProvider = serviceProvider; //save references to dte events buildEvents = dte.Events.BuildEvents; genericCommandEvents = dte.Events.CommandEvents; menuCommandEvents = dte.Events.get_CommandEvents(MenuEventGuid); debuggerEvents = dte.Events.DebuggerEvents; documentEvents = dte.Events.DocumentEvents; findEvents = dte.Events.FindEvents; miscFileEvents = dte.Events.MiscFilesEvents; outputWindowEvents = dte.Events.OutputWindowEvents; selectionEvents = dte.Events.SelectionEvents; solutionEvents = dte.Events.SolutionEvents; solutionItemsEvents = dte.Events.SolutionItemsEvents; textEditorEvents = dte.Events.TextEditorEvents; //attach osbide requests _osbideEvents = osbideEvents; _osbideEvents.SolutionSubmitRequest += new EventHandler <SubmitAssignmentArgs>(OsbideSolutionSubmitted); _osbideEvents.SolutionDownloaded += new EventHandler <SolutionDownloadedEventArgs>(OsbideSolutionDownloaded); _osbideEvents.SubmitEventRequested += new EventHandler <SubmitEventArgs>(SubmitEventRequested); //attach listeners for dte events //build events buildEvents.OnBuildBegin += new _dispBuildEvents_OnBuildBeginEventHandler(OnBuildBegin); buildEvents.OnBuildDone += new _dispBuildEvents_OnBuildDoneEventHandler(OnBuildDone); //generic command events genericCommandEvents.AfterExecute += new _dispCommandEvents_AfterExecuteEventHandler(GenericCommand_AfterCommandExecute); genericCommandEvents.BeforeExecute += new _dispCommandEvents_BeforeExecuteEventHandler(GenericCommand_BeforeCommandExecute); //menu-related command command menuCommandEvents.AfterExecute += new _dispCommandEvents_AfterExecuteEventHandler(MenuCommand_AfterExecute); menuCommandEvents.BeforeExecute += new _dispCommandEvents_BeforeExecuteEventHandler(MenuCommand_BeforeExecute); //debugger events debuggerEvents.OnContextChanged += new _dispDebuggerEvents_OnContextChangedEventHandler(OnContextChanged); debuggerEvents.OnEnterBreakMode += new _dispDebuggerEvents_OnEnterBreakModeEventHandler(OnEnterBreakMode); debuggerEvents.OnEnterDesignMode += new _dispDebuggerEvents_OnEnterDesignModeEventHandler(OnEnterDesignMode); debuggerEvents.OnEnterRunMode += new _dispDebuggerEvents_OnEnterRunModeEventHandler(OnEnterRunMode); debuggerEvents.OnExceptionNotHandled += new _dispDebuggerEvents_OnExceptionNotHandledEventHandler(OnExceptionNotHandled); debuggerEvents.OnExceptionThrown += new _dispDebuggerEvents_OnExceptionThrownEventHandler(OnExceptionThrown); //document events documentEvents.DocumentClosing += new _dispDocumentEvents_DocumentClosingEventHandler(DocumentClosing); documentEvents.DocumentOpened += new _dispDocumentEvents_DocumentOpenedEventHandler(DocumentOpened); documentEvents.DocumentSaved += new _dispDocumentEvents_DocumentSavedEventHandler(DocumentSaved); //find events findEvents.FindDone += new _dispFindEvents_FindDoneEventHandler(FindDone); //misc file events miscFileEvents.ItemAdded += new _dispProjectItemsEvents_ItemAddedEventHandler(ProjectItemAdded); miscFileEvents.ItemRemoved += new _dispProjectItemsEvents_ItemRemovedEventHandler(ProjectItemRemoved); miscFileEvents.ItemRenamed += new _dispProjectItemsEvents_ItemRenamedEventHandler(ProjectItemRenamed); //output window events outputWindowEvents.PaneUpdated += new _dispOutputWindowEvents_PaneUpdatedEventHandler(OutputPaneUpdated); //selection events selectionEvents.OnChange += new _dispSelectionEvents_OnChangeEventHandler(SelectionChange); //solution events solutionEvents.BeforeClosing += new _dispSolutionEvents_BeforeClosingEventHandler(SolutionBeforeClosing); solutionEvents.Opened += new _dispSolutionEvents_OpenedEventHandler(SolutionOpened); solutionEvents.ProjectAdded += new _dispSolutionEvents_ProjectAddedEventHandler(ProjectAdded); solutionEvents.Renamed += new _dispSolutionEvents_RenamedEventHandler(SolutionRenamed); //solution item events solutionItemsEvents.ItemAdded += new _dispProjectItemsEvents_ItemAddedEventHandler(SolutionItemAdded); solutionItemsEvents.ItemRemoved += new _dispProjectItemsEvents_ItemRemovedEventHandler(SolutionItemRemoved); solutionItemsEvents.ItemRenamed += new _dispProjectItemsEvents_ItemRenamedEventHandler(SolutionItemRenamed); //text editor events textEditorEvents.LineChanged += new _dispTextEditorEvents_LineChangedEventHandler(EditorLineChanged); }
public static void InitializeListeners() { _dte = ServiceProvider.GlobalProvider.GetService(typeof(DTE)) as DTE2; //register for F5 hit event and start previewing if selected document is jsreport _debugCommandEvent = _dte.Events.CommandEvents["{5EFC7975-14BC-11CF-9B2B-00AA00573819}", 295]; _debugCommandEvent.BeforeExecute += (string guid, int id, object @in, object @out, ref bool @default) => { if (_dte.ActiveDocument != null && _dte.ActiveDocument.FullName.Contains(".jsrep") && !_dte.ActiveDocument.FullName.Contains(".png") && !_dte.ActiveDocument.FullName.Contains(".json")) { @default = true; DoPreviewActiveItem().Wait(); } }; //new project item should clear schemas cache, so new jsrep.json is visible in combo _cteateProjectItemEvent = _dte.Events.CommandEvents["{5EFC7975-14BC-11CF-9B2B-00AA00573819}", 220]; _cteateProjectItemEvent.AfterExecute += (string guid, int id, object @in, object @out) => { ReportingServerManagerAdapter.ClearCache(); foreach (Window window in _dte.Windows) { var jsrepEditorPane = window.Object as JsRepEditorPane; if (jsrepEditorPane != null) { jsrepEditorPane.MarkRerfeshRequired(); } } }; //saving ReportingStartup.cs should restart current server manager _documentEvents = _dte.Events.DocumentEvents; _documentEvents.DocumentSaved += async document => { if (document.FullName.ToLower().Contains("reportingstartup")) { lock (_locker) { if (_configReloadInProgress) { return; } _configReloadInProgress = true; } try { Trace.TraceInformation("Reloading because of reportingstartup"); await ReportingServerManagerAdapter.StopAsync(); foreach (Window window in _dte.Windows) { var jsrepEditorPane = window.Object as JsRepEditorPane; if (jsrepEditorPane != null) { jsrepEditorPane.MarkRerfeshRequired(); } } } finally { _configReloadInProgress = false; Trace.TraceInformation("Reloading done"); } } }; ReportingServerManagerAdapter = new ReportingServerManagerAdapter(_dte); }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override async System.Threading.Tasks.Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress) { // Switches to the UI thread in order to consume some services used in command initialization await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); await RegisterVsServices(); var vsOutputWindow = VsServiceProvider.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow; mOutputController = new OutputWindowController(); mOutputController.Initialize(this, vsOutputWindow); mRunningDocTableEvents = new RunningDocTableEvents(this); mErrorWindow = new ErrorWindowController(this); mCommandsController = new CommandsController(this); #region Get Pointer to IVsSolutionEvents if (VsServiceProvider.TryGetService(typeof(SVsSolution), out object vsSolutionService)) { var vsSolution = vsSolutionService as IVsSolution; UnadviseSolutionEvents(vsSolution); AdviseSolutionEvents(vsSolution); } #endregion // Get the build and command events from DTE if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { var dte2 = dte as DTE2; mBuildEvents = dte2.Events.BuildEvents; mCommandEvents = dte2.Events.CommandEvents; mDteEvents = dte2.Events.DTEEvents; } // Get the general clang option page var generalOptions = (ClangGeneralOptionsView)GetDialogPage(typeof(ClangGeneralOptionsView)); // Detect the first install if (null == generalOptions.Version || string.IsNullOrWhiteSpace(generalOptions.Version)) { ShowToolbare(); // Show the toolbar on the first install } var currentVersion = GetPackageVersion(); if (0 != string.Compare(generalOptions.Version, currentVersion)) { mOutputController.Show(); mOutputController.Write($"🎉\tClang Power Tools was upgraded to v{currentVersion}\n" + $"\tCheck out what's new at http://www.clangpowertools.com/CHANGELOG"); generalOptions.Version = currentVersion; generalOptions.SaveSettingsToStorage(); } await InitializeAsyncCommands(); RegisterToVsEvents(); await base.InitializeAsync(cancellationToken, progress); }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString())); base.Initialize(); // Add our command handlers for menu (commands must exist in the .vsct file) OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (null != mcs) { // Create the command for the menu item. CommandID menuCommandID = new CommandID(GuidList.guidDuplicateFileCmdSet, (int)PkgCmdIDList.cmdidDuplicateCmd); MenuCommand menuItem = new MenuCommand(MenuItemCallbackDuplicate, menuCommandID); mcs.AddCommand(menuItem); } // Add our command handlers for menu (commands must exist in the .vsct file) if (null != mcs) { // Create the command for the menu item. CommandID menuCommandID = new CommandID(GuidList.guidRefreshCmdSet, (int)PkgCmdIDList.cmdidRefreshCmd); MenuCommand menuItem = new MenuCommand(MenuItemCallbackRefresh, menuCommandID); mcs.AddCommand(menuItem); } // Add our command handlers for menu (commands must exist in the .vsct file) if (null != mcs) { // Create the command for the menu item. CommandID menuCommandID = new CommandID(GuidList.guidShowHelpCmdSet, (int)PkgCmdIDList.cmdidShowHelp); MenuCommand menuItem = new MenuCommand(MenuItemCallbackShowHelp, menuCommandID); mcs.AddCommand(menuItem); } // Override Edit.Delete command _applicationObject = (DTE)GetService(typeof(DTE)); var command = _applicationObject.Commands.Item("Edit.Delete"); _removeEvent = _applicationObject.Events.CommandEvents[command.Guid, command.ID]; _removeEvent.BeforeExecute += OnBeforeDeleteCommand; }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress) { // Switches to the UI thread in order to consume some services used in command initialization await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); await RegisterVsServicesAsync(); mCommandController = new CommandController(this); CommandTestUtility.CommandController = mCommandController; var vsOutputWindow = VsServiceProvider.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow; mOutputWindowController = new OutputWindowController(); mOutputWindowController.Initialize(this, vsOutputWindow); mRunningDocTableEvents = new RunningDocTableEvents(this); mErrorWindowController = new ErrorWindowController(this); #region Get Pointer to IVsSolutionEvents if (VsServiceProvider.TryGetService(typeof(SVsSolution), out object vsSolutionService)) { var vsSolution = vsSolutionService as IVsSolution; UnadviseSolutionEvents(vsSolution); AdviseSolutionEvents(vsSolution); } #endregion // Get the build and command events from DTE if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { var dte2 = dte as DTE2; mBuildEvents = dte2.Events.BuildEvents; mCommandEvents = dte2.Events.CommandEvents; mDteEvents = dte2.Events.DTEEvents; } DispatcherHandler.Initialize(dte as DTE2); SettingsProvider.Initialize(this); // Detect the first install if (string.IsNullOrWhiteSpace(SettingsProvider.GeneralSettings.Version)) { ShowToolbare(); // Show the toolbar on the first install } if (string.IsNullOrWhiteSpace(SettingsProvider.GeneralSettings.Version) || 0 > string.Compare(SettingsProvider.GeneralSettings.Version, "5.0.0")) { System.Diagnostics.Process.Start(new ProcessStartInfo("https://clangpowertools.com/blog/future-of-clang-power-tools.html")); } var currentVersion = PackageUtility.GetVersion(); if (!string.IsNullOrWhiteSpace(currentVersion) && 0 > string.Compare(SettingsProvider.GeneralSettings.Version, currentVersion)) { mOutputWindowController.Clear(); mOutputWindowController.Show(); mOutputWindowController.Write($"🎉\tClang Power Tools was upgraded to v{currentVersion}\n" + $"\tCheck out what's new at http://www.clangpowertools.com/CHANGELOG"); SettingsProvider.GeneralSettings.Version = currentVersion; } SettingsHandler.SaveGeneralSettings(); await mCommandController.InitializeCommandsAsync(this); mLicenseController = new LicenseController(); RegisterToEvents(); await mLicenseController.CheckLicenseAsync(); await base.InitializeAsync(cancellationToken, progress); }
///////////////////////////////////////////////////////////////////////////// // Overridden Package Implementation #region Package Members /// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this)); base.Initialize(); this.dte2 = this.GetService(typeof(SDTE)) as DTE2; if (this.dte2 == null) { Log.LogError("VSPackage.Initialize() could not obtain DTE2 reference"); return; } this.RefreshMSBuildOutputVerbositySetting(); // Get solution build manager this.solutionBuildManager = ServiceProvider.GlobalProvider.GetService(typeof(SVsSolutionBuildManager)) as IVsSolutionBuildManager2; if (this.solutionBuildManager != null) { this.solutionBuildManager.AdviseUpdateSolutionEvents(this, out this.updateSolutionEventsCookie); } IVsOutputWindow outputWindow = this.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow; if (outputWindow == null) { Log.LogError("VSPackage.Initialize() could not obtain IVsOutputWindow reference"); return; } Guid buildPaneGuid = VSConstants.GUID_BuildOutputWindowPane; int hResult = outputWindow.GetPane(ref buildPaneGuid, out this.buildOutputWindowPane); if (hResult != VSConstants.S_OK || this.buildOutputWindowPane == null) { Log.LogError("VSPackage.Initialize() could not obtain IVsOutputWindowPane reference"); return; } GuidAttribute VSStd97CmdIDGuidAttribute = typeof(VSConstants.VSStd97CmdID).GetCustomAttributes(typeof(GuidAttribute), true)[0] as GuidAttribute; Debug.Assert(VSStd97CmdIDGuidAttribute != null, "VSStd97CmdIDGuidAttribute != null"); this.VSStd97CmdIDGuid = "{" + VSStd97CmdIDGuidAttribute.Value + "}"; GuidAttribute VSStd2KCmdIDGuidAttribute = typeof(VSConstants.VSStd2KCmdID).GetCustomAttributes(typeof(GuidAttribute), true)[0] as GuidAttribute; Debug.Assert(VSStd2KCmdIDGuidAttribute != null, "VSStd2KCmdIDGuidAttribute != null"); this.VSStd2KCmdIDGuid = "{" + VSStd2KCmdIDGuidAttribute.Value + "}"; this.commandEvents = this.dte2.Events.CommandEvents; this.commandEvents.BeforeExecute += this.CommandEvents_BeforeExecute; }
void VsShellPropertyEvents_AfterShellPropertyChanged(object sender, VsShellPropertyEventsHandler.ShellPropertyChangeEventArgs e) { SafeExecute(() => { // when zombie state changes to false, finish package initialization //! DO NOT USE CODE WHICH MAY EXECUTE FOR LONG TIME HERE if ((int)__VSSPROPID.VSSPROPID_Zombie == e.PropId) { if ((bool)e.Var == false) { var dte2 = ServiceProvider.GetDte2(); Events = dte2.Events as Events2; DTEEvents = Events.DTEEvents; SolutionEvents = Events.SolutionEvents; DocumentEvents = Events.DocumentEvents; WindowEvents = Events.WindowEvents; DebuggerEvents = Events.DebuggerEvents; CommandEvents = Events.CommandEvents; SelectionEvents = Events.SelectionEvents; DelayedInitialise(); } } }); }
public VisualStudioEventHandler(DTEEvents dTEEvents, CommandEvents closeCommandEvents, ProcessStartInfo processStartInfo) { _dTEEvents = dTEEvents; _closeCommandEvents = closeCommandEvents; _startInfo = processStartInfo; dTEEvents.OnBeginShutdown += DTEEvents_OnBeginShutdown; if (closeCommandEvents != null) { closeCommandEvents.AfterExecute += CommandEvents_AfterExecute; } }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the /// place where you can put all the initilaization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { base.Initialize(); OutputWindowHandler.Initialize(GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow); _licenseReplacer = new LicenseHeaderReplacer(this); _dte = GetService(typeof(DTE)) as DTE2; _addedItems = new Stack <ProjectItem>(); var buttonHandlerFactory = new ButtonHandlerFactory(this, _licenseReplacer); //register commands OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (mcs != null) { _addLicenseHeaderCommand = RegisterCommand(mcs, PkgCmdIDList.cmdIdAddLicenseHeader, AddLicenseHeaderCallback); _removeLicenseHeaderCommand = RegisterCommand(mcs, PkgCmdIDList.cmdIdRemoveLicenseHeader, RemoveLicenseHeaderCallback); _addLicenseHeaderCommand.BeforeQueryStatus += QueryEditCommandStatus; _addLicenseHeaderToProjectItemCommand = RegisterCommand(mcs, PkgCmdIDList.cmdIdAddLicenseHeaderToProjectItem, AddLicenseHeaderToProjectItemCallback); _removeLicenseHeaderFromProjectItemCommand = RegisterCommand(mcs, PkgCmdIDList.cmdIdRemoveLicenseHeaderFromProjectItem, RemoveLicenseHeaderFromProjectItemCallback); _addLicenseHeaderToProjectItemCommand.BeforeQueryStatus += QueryProjectItemCommandStatus; _addLicenseHeadersToAllFilesCommand = RegisterCommand(mcs, PkgCmdIDList.cmdIdAddLicenseHeadersToAllFiles, AddLicenseHeadersToAllFilesCallback); _removeLicenseHeadersFromAllFilesCommand = RegisterCommand(mcs, PkgCmdIDList.cmdIdRemoveLicenseHeadersFromAllFiles, RemoveLicenseHeadersFromAllFilesCallback); _addLicenseHeadersToAllFilesCommand.BeforeQueryStatus += QueryAllFilesCommandStatus; RegisterCommand(mcs, PkgCmdIDList.cmdIdAddLicenseHeaderDefinitionFile, AddLicenseHeaderDefinitionFileCallback); RegisterCommand(mcs, PkgCmdIDList.cmdIdAddExistingLicenseHeaderDefinitionFile, AddExistingLicenseHeaderDefinitionFileCallback); RegisterCommand(mcs, PkgCmdIDList.cmdIdLicenseHeaderOptions, LicenseHeaderOptionsCallback); RegisterCommand(mcs, PkgCmdIDList.cmdIdAddLicenseHeaderToAllProjects, buttonHandlerFactory.CreateAddLicenseHeaderToAllProjectsButtonHandler().HandleButton); RegisterCommand(mcs, PkgCmdIDList.cmdIdRemoveLicenseHeaderFromAllProjects, RemoveLicenseHeaderFromAllProjectsCallback); } //register ItemAdded event handler var events = _dte.Events as Events2; if (events != null) { _projectItemEvents = events.ProjectItemsEvents; //we need to keep a reference, otherwise the object is garbage collected and the event won't be fired _projectItemEvents.ItemAdded += ItemAdded; } //register event handlers for linked commands var page = (OptionsPage)GetDialogPage(typeof(OptionsPage)); if (page != null) { foreach (var command in page.LinkedCommands) { command.Events = _dte.Events.CommandEvents[command.Guid, command.Id]; switch (command.ExecutionTime) { case ExecutionTime.Before: command.Events.BeforeExecute += BeforeLinkedCommandExecuted; break; case ExecutionTime.After: command.Events.AfterExecute += AfterLinkedCommandExecuted; break; } } page.LinkedCommandsChanged += CommandsChanged; //register global event handler for ItemAdded _commandEvents = _dte.Events.CommandEvents; _commandEvents.BeforeExecute += BeforeAnyCommandExecuted; } }
protected override void Initialize() { base.Initialize(); _dte = (DTE2) GetGlobalService(typeof (DTE)); Active = true; _buildEvents = _dte.Events.BuildEvents; const string VSStd97CmdIDGuid = "{5efc7975-14bc-11cf-9b2b-00aa00573819}"; _buildCancel = _dte.Events.get_CommandEvents(VSStd97CmdIDGuid, (int)VSConstants.VSStd97CmdID.CancelBuild); _buildCancel.BeforeExecute += buildCancel_BeforeExecute; //Since Visual Studio 2012 has parallel builds, we only want to cancel the build process once. //This makes no difference for older versions of Visual Studio. _buildEvents.OnBuildBegin += delegate { _canExecute = true; }; _buildEvents.OnBuildDone += delegate { _canExecute = false; }; _buildEvents.OnBuildProjConfigDone += OnProjectBuildFinished; _selectionMonitor = (IVsMonitorSelection) GetGlobalService(typeof (SVsShellMonitorSelection)); var solutionHasMultipleProjects = VSConstants.UICONTEXT.SolutionHasMultipleProjects_guid; _selectionMonitor.GetCmdUIContextCookie(ref solutionHasMultipleProjects, out _solutionHasMultipleProjectsCookie); _selectionMonitor.AdviseSelectionEvents(this, out _selectionEventsCookie); InitializeMenuItem(); }
///////////////////////////////////////////////////////////////////////////// // Overridden Package Implementation #region Package Member /// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress) { await JoinableTaskFactory.SwitchToMainThreadAsync(DisposalToken); Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString())); base.Initialize(); var m_objDTE = (DTE)GetService(typeof(DTE)); Assumes.Present(m_objDTE); commandEvents = m_objDTE.Events.CommandEvents; commandEvents.BeforeExecute += delegate(string Guid, int ID, object CustomIn, object CustomOut, ref bool CancelDefault) { ThreadHelper.ThrowIfNotOnUIThread(); var objCommand = m_objDTE.Commands.Item(Guid, ID); if (objCommand != null) { var bindings = objCommand.Bindings as object[]; if (bindings != null && bindings.Any()) { var shortcuts = GetBindings(bindings); if (shortcuts.Any()) { lock (typeof(ShortcutCommanderPackage)) { var shortcutActive = false; foreach (var shortcut in shortcuts) { var sequenceActive = false; var shortcutSequences = shortcut.Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); foreach (var shortcutSequence in shortcutSequences) { var keyActive = true; var shortcutKeys = shortcutSequence.Split('+'); foreach (var shortcutKey in shortcutKeys) { Key key; switch (shortcutKey) { case "Ctrl": key = Key.LeftCtrl; break; case "Alt": key = Key.LeftAlt; break; case "Shift": key = Key.LeftShift; break; case "Bkspce": key = Key.Back; break; case "Del": key = Key.Delete; break; case "Ins": key = Key.Insert; break; case "PgDn": key = Key.PageDown; break; case "PgUp": key = Key.PageUp; break; case "Down Arrow": key = Key.Down; break; case "Up Arrow": key = Key.Up; break; case "Left Arrow": key = Key.Left; break; case "Right Arrow": key = Key.Right; break; default: if (!Enum.TryParse(shortcutKey, out key)) { if (Debugger.IsAttached) { Debugger.Break(); } continue; } break; } if (!Keyboard.IsKeyDown(key)) { keyActive = false; break; } } if (keyActive) { sequenceActive = true; break; } } if (sequenceActive) { shortcutActive = true; break; } } if (!shortcutActive) { if (window != null) { window.Close(); window = null; } window = new HotkeyWindow(); var contentBlock = window.CommandText.Children; contentBlock.Clear(); var space = " " + Convert.ToChar(160) + " "; for (var i = 0; i < shortcuts.Length; i++) { if (i > 0) { contentBlock.Add(new TextBlock(new Run(space + " or " + space)) { Opacity = 0.5 }); } contentBlock.Add(new TextBlock(new Run(shortcuts[i]))); } window.Show(); } } } } } }; }
void IDTExtensibility2.OnDisconnection( Extensibility.ext_DisconnectMode dmDisconnectMode, ref System.Array arrCustom ) { // Remove command handlers _cmdevDebugStart.BeforeExecute -= new EnvDTE._dispCommandEvents_BeforeExecuteEventHandler( OnBeforeRun ); _cmdevDebugStart.AfterExecute -= new EnvDTE._dispCommandEvents_AfterExecuteEventHandler( OnAfterRun ); _cmdevDebugStart = null; _cmdevNoDebugStart.BeforeExecute -= new EnvDTE._dispCommandEvents_BeforeExecuteEventHandler( OnBeforeRun ); _cmdevNoDebugStart.AfterExecute -= new EnvDTE._dispCommandEvents_AfterExecuteEventHandler( OnAfterRun ); _cmdevNoDebugStart = null; _pApplication = null; _pAddInInstance = null; _pf = null; }
private void InitializeAsync() { ThreadHelper.ThrowIfNotOnUIThread(); dte2_buildevents = dte2.Events.BuildEvents; dte2_cmdevents = dte2.Events.CommandEvents; }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the /// place where you can put all the initilaization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize () { base.Initialize (); _licenseReplacer = new LicenseHeaderReplacer (this); _dte = GetService (typeof (DTE)) as DTE2; _addedItems = new Stack<ProjectItem>(); //register commands OleMenuCommandService mcs = GetService (typeof (IMenuCommandService)) as OleMenuCommandService; if (mcs != null) { _addLicenseHeaderCommand = RegisterCommand (mcs, PkgCmdIDList.cmdIdAddLicenseHeader, AddLicenseHeaderCallback); _removeLicenseHeaderCommand = RegisterCommand (mcs, PkgCmdIDList.cmdIdRemoveLicenseHeader, RemoveLicenseHeaderCallback); _addLicenseHeaderCommand.BeforeQueryStatus += QueryEditCommandStatus; _addLicenseHeaderToProjectItemCommand = RegisterCommand (mcs, PkgCmdIDList.cmdIdAddLicenseHeaderToProjectItem, AddLicenseHeaderToProjectItemCallback); _removeLicenseHeaderFromProjectItemCommand = RegisterCommand (mcs, PkgCmdIDList.cmdIdRemoveLicenseHeaderFromProjectItem, RemoveLicenseHeaderFromProjectItemCallback); _addLicenseHeaderToProjectItemCommand.BeforeQueryStatus += QueryProjectItemCommandStatus; _addLicenseHeadersToAllFilesCommand = RegisterCommand (mcs, PkgCmdIDList.cmdIdAddLicenseHeadersToAllFiles, AddLicenseHeadersToAllFilesCallback); _removeLicenseHeadersFromAllFilesCommand = RegisterCommand (mcs, PkgCmdIDList.cmdIdRemoveLicenseHeadersFromAllFiles, RemoveLicenseHeadersFromAllFilesCallback); _addLicenseHeadersToAllFilesCommand.BeforeQueryStatus += QueryAllFilesCommandStatus; RegisterCommand (mcs, PkgCmdIDList.cmdIdAddLicenseHeaderDefinitionFile, AddLicenseHeaderDefinitionFileCallback); RegisterCommand (mcs, PkgCmdIDList.cmdIdAddExistingLicenseHeaderDefinitionFile, AddExistingLicenseHeaderDefinitionFileCallback); RegisterCommand (mcs, PkgCmdIDList.cmdIdLicenseHeaderOptions, LicenseHeaderOptionsCallback); } //register ItemAdded event handler var events = _dte.Events as Events2; if (events != null) { _projectItemEvents = events.ProjectItemsEvents; //we need to keep a reference, otherwise the object is garbage collected and the event won't be fired _projectItemEvents.ItemAdded += ItemAdded; } //register event handlers for linked commands var page = (OptionsPage) GetDialogPage (typeof (OptionsPage)); if (page != null) { foreach (var command in page.LinkedCommands) { command.Events = _dte.Events.CommandEvents[command.Guid, command.Id]; switch (command.ExecutionTime) { case ExecutionTime.Before: command.Events.BeforeExecute += BeforeLinkedCommandExecuted; break; case ExecutionTime.After: command.Events.AfterExecute += AfterLinkedCommandExecuted; break; } } page.LinkedCommandsChanged += CommandsChanged; //register global event handler for ItemAdded _commandEvents = _dte.Events.CommandEvents; _commandEvents.BeforeExecute += BeforeAnyCommandExecuted; } }
// Step 4: // Define a method to add subscription of the Project.AddReference command. /////////////////////////////////////////////////////////////////////////////// // Subscribe to the BeforeExecute and AfterExecute events, add our process into // the command handler. // public void AddSubscription() { // "{1496A755-94DE-11D0-8C3F-00C04FC2AAE2}, 1113" Guid-ID pair refer to // Project.AddReference command. // About how to get the Guid and ID of the specific command, please take a // look at this link on Dr.eX's blog: // http://blogs.msdn.com/dr._ex/archive/2007/04/17/using-enablevsiplogging- // to-identify-menus-and-commands-with-vs-2005-sp1.aspx try { addReferenceEvents = _applicationObject.Events.get_CommandEvents( "{1496A755-94DE-11D0-8C3F-00C04FC2AAE2}", 1113); addReferenceEvents.BeforeExecute += new _dispCommandEvents_BeforeExecuteEventHandler (addReferenceEvents_BeforeExecute); addReferenceEvents.AfterExecute += new _dispCommandEvents_AfterExecuteEventHandler (addReferenceEvents_AfterExecute); } catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.Message); } }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { base.Initialize(); dte = GetService(typeof (DTE)) as DTE; if (null == dte) { throw new ArgumentNullException(nameof(dte)); } var pane = GetService(typeof(SVsGeneralOutputWindowPane)) as IVsOutputWindowPane; if (null == pane) { throw new ArgumentNullException(nameof(pane)); } output = new VisualStudioOutputPaneProvider(pane); formatDocumentEvent = dte.Events.CommandEvents[VsStd2KCmdIdGuid, (int) VSConstants.VSStd2KCmdID.FORMATDOCUMENT]; saveProjectItemEvent = dte.Events.CommandEvents[VsStd97CmdIdGuid, (int) VSConstants.VSStd97CmdID.SaveProjectItem]; factory = new CommandFactory(dte, output); formatDocumentEvent.BeforeExecute += OnFormatDocumentBeforeExecute; saveProjectItemEvent.BeforeExecute += OnSaveProjectItemBeforeExecute; }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override async System.Threading.Tasks.Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress) { // Switches to the UI thread in order to consume some services used in command initialization await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); await RegisterVsServices(); mCommandsController = new CommandsController(this); SettingsProvider.Initialize(this); var vsOutputWindow = VsServiceProvider.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow; mOutputWindowController = new OutputWindowController(); mOutputWindowController.Initialize(this, vsOutputWindow); //mCommandsController.ClangCommandMessageEvent += mOutputWindowController.Write; //PowerShellWrapper.DataHandler += mOutputWindowController.OutputDataReceived; //PowerShellWrapper.DataErrorHandler += mOutputWindowController.OutputDataErrorReceived; //PowerShellWrapper.ExitedHandler += mOutputWindowController.ClosedDataConnection; mRunningDocTableEvents = new RunningDocTableEvents(this); mErrorWindowController = new ErrorWindowController(this); //mOutputWindowController.ErrorDetectedEvent += mErrorWindowController.OnErrorDetected; #region Get Pointer to IVsSolutionEvents if (VsServiceProvider.TryGetService(typeof(SVsSolution), out object vsSolutionService)) { var vsSolution = vsSolutionService as IVsSolution; UnadviseSolutionEvents(vsSolution); AdviseSolutionEvents(vsSolution); } #endregion // Get the build and command events from DTE if (VsServiceProvider.TryGetService(typeof(DTE), out object dte)) { var dte2 = dte as DTE2; mBuildEvents = dte2.Events.BuildEvents; mCommandEvents = dte2.Events.CommandEvents; mDteEvents = dte2.Events.DTEEvents; } DispatcherHandler.Initialize(dte as DTE2); // Get the general clang option page var generalSettings = SettingsProvider.GetSettingsPage(typeof(ClangGeneralOptionsView)) as ClangGeneralOptionsView; // Detect the first install if (string.IsNullOrWhiteSpace(generalSettings.Version)) { ShowToolbare(); // Show the toolbar on the first install } var currentVersion = GetPackageVersion(); if (0 > string.Compare(generalSettings.Version, currentVersion)) { mOutputWindowController.Clear(); mOutputWindowController.Show(); mOutputWindowController.Write($"🎉\tClang Power Tools was upgraded to v{currentVersion}\n" + $"\tCheck out what's new at http://www.clangpowertools.com/CHANGELOG"); generalSettings.Version = currentVersion; generalSettings.SaveSettingsToStorage(); } await mCommandsController.InitializeAsyncCommands(this); //mCommandsController.HierarchyDetectedEvent += mOutputWindowController.OnFileHierarchyDetected; //mOutputWindowController.MissingLlvmEvent += mCommandsController.OnMissingLLVMDetected; //RegisterToCPTEvents(); //RegisterToVsEvents(); RegisterToEvents(); await base.InitializeAsync(cancellationToken, progress); }
/// <summary>Implements the OnStartupComplete method of the IDTExtensibility2 interface. Receives notification /// that the host application has completed loading.</summary> /// <param term='custom'>Array of parameters that are host application specific.</param> /// <seealso class='IDTExtensibility2' /> public void OnStartupComplete(ref Array custom) { // Get a handle to the Execute SQL command ce = _addInInstance.DTE.Events.get_CommandEvents("{52692960-56BC-4989-B5D3-94C47A513E8D}", 1); // Subscribe to the AfterExecute event handler to log queries ce.AfterExecute += new _dispCommandEvents_AfterExecuteEventHandler(CommandEvents_AfterExecute); }
private void ItemAdded (ProjectItem item) { //An item was added. Check if we should insert a header automatically. var page = (OptionsPage) GetDialogPage (typeof (OptionsPage)); if (page != null && page.InsertInNewFiles && item != null) { //Normally the header should be inserted here, but that might interfere with the command //currently being executed, so we wait until it is finished. _currentCommandEvents = _dte.Events.CommandEvents[_currentCommandGuid, _currentCommandId]; _currentCommandEvents.AfterExecute += FinishedAddingItem; _addedItems.Push (item); } }
public BuildContext(IPackageContext packageContext, FindProjectItemDelegate findProjectItem) { _buildedProjects = new BuildedProjectsCollection(); _buildingProjects = new List<ProjectItem>(); _buildingProjectsLockObject = ((ICollection)_buildingProjects).SyncRoot; _packageContext = packageContext; _findProjectItem = findProjectItem; Events dteEvents = packageContext.GetDTE().Events; _buildEvents = dteEvents.BuildEvents; _windowEvents = dteEvents.WindowEvents; _commandEvents = dteEvents.CommandEvents; _buildEvents.OnBuildBegin += BuildEvents_OnBuildBegin; _buildEvents.OnBuildDone += (s, e) => BuildEvents_OnBuildDone(); _buildEvents.OnBuildProjConfigBegin += BuildEvents_OnBuildProjectBegin; _buildEvents.OnBuildProjConfigDone += BuildEvents_OnBuildProjectDone; _windowEvents.WindowActivated += WindowEvents_WindowActivated; _commandEvents.AfterExecute += CommandEvents_AfterExecute; }
/// <summary> /// Implements the OnStartupComplete method of the IDTExtensibility2 interface. Receives notification that the host application has completed loading. /// </summary> /// <param name="custom">Array of parameters that are host application specific.</param> /// <seealso cref="IDTExtensibility2"/> public void OnStartupComplete(ref Array custom) { this.eventsOnDocs = this.events.get_DocumentEvents(); this.eventsOnProjectItems = this.events.ProjectItemsEvents; this.eventsOnSolution = this.events.SolutionEvents; this.eventsOnBuild = this.events.BuildEvents; this.eventsOnCommand = this.events.CommandEvents; this.eventsOnCommand.BeforeExecute += new _dispCommandEvents_BeforeExecuteEventHandler(this.CommandEvents_BeforeExecute); this.eventsOnSolution.Opened += new _dispSolutionEvents_OpenedEventHandler(eventsOnSolution_Opened); this.eventsOnSolution.ProjectRemoved += new _dispSolutionEvents_ProjectRemovedEventHandler(this.SolutionEvents_ProjectRemoved); this.eventsOnSolution.AfterClosing += new _dispSolutionEvents_AfterClosingEventHandler(this.EventsOnSolution_AfterClosing); this.eventsOnProjectItems.ItemRenamed += new _dispProjectItemsEvents_ItemRenamedEventHandler(this.ProjectItemsEvents_ItemRenamed); this.eventsOnProjectItems.ItemAdded += new _dispProjectItemsEvents_ItemAddedEventHandler(this.ProjectItemsEvents_ItemAdded); this.eventsOnProjectItems.ItemRemoved += new _dispProjectItemsEvents_ItemRemovedEventHandler(this.ProjectItemsEvents_ItemRemoved); this.eventsOnDocs.DocumentSaved += new _dispDocumentEvents_DocumentSavedEventHandler(this.DocumentEvents_DocumentSaved); this.tasks = new TaskList(this.App); try { this.LoadActions(); } catch (Exception ex) { this.OutputWindowWriteText("Error in load action: " + ex.ToString()); } try { if (Settings.Instance().LessSyntaxHighlighting) { this.TreatLessAsCss(true); } } catch (Exception ex) { this.OutputWindowWriteText("Error in TreatLessAsCss: " + ex.ToString()); } // ensures the output window is lazy loaded so the multiple threads don't compete for and end up creating several if (Settings.Instance().ShowDetailLog) { this.OutputWindowWriteText("Ready"); } }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the /// place where you can put all the initilaization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { base.Initialize(); OutputWindowHandler.Initialize(GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow); _licenseReplacer = new LicenseHeaderReplacer(this); _dte = GetService(typeof(DTE)) as DTE2; _addedItems = new Stack <ProjectItem>(); var buttonHandlerFactory = new ButtonHandlerFactory(this, _licenseReplacer); //register commands OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (mcs != null) { AddNewSolutionLicenseHeaderDefinitionFileCommand.Initialize( () => { var page2 = (DefaultLicenseHeaderPage)GetDialogPage(typeof(DefaultLicenseHeaderPage)); return(page2.LicenseHeaderFileText); }); OpenSolutionLicenseHeaderDefinitionFileCommand.Initialize(); RemoveSolutionLicenseHeaderDefinitionFileCommand.Initialize(); _addHeaderCommand = RegisterCommand(mcs, PkgCmdIDList.cmdIdAddLicenseHeader, AddLicenseHeaderCallback); _removeHeaderCommand = RegisterCommand(mcs, PkgCmdIDList.cmdIdRemoveLicenseHeader, RemoveLicenseHeaderCallback); _addHeaderCommand.BeforeQueryStatus += QueryEditCommandStatus; _addHeaderToProjectItemCommand = RegisterCommand(mcs, PkgCmdIDList.cmdIdAddLicenseHeaderToProjectItem, AddLicenseHeaderToProjectItemCallback); _removeHeaderFromProjectItemCommand = RegisterCommand(mcs, PkgCmdIDList.cmdIdLicenseRemoveHeaderFromProjectItem, RemoveLicenseHeaderFromProjectItemCallback); _addHeaderToProjectItemCommand.BeforeQueryStatus += QueryProjectItemCommandStatus; _addHeadersToAllFilesInProjectCommand = RegisterCommand(mcs, PkgCmdIDList.cmdIdAddLicenseHeadersToAllFilesInProject, AddLicenseHeadersToAllFilesInProjectCallback); _removeHeadersFromAllFilesInProjectCommand = RegisterCommand(mcs, PkgCmdIDList.cmdIdRemoveLicenseHeadersFromAllFilesInProject, RemoveLicenseHeadersFromAllFilesInProjectCallback); _addHeadersToAllFilesInProjectCommand.BeforeQueryStatus += QueryAllFilesCommandStatus; _addNewSolutionHeaderDefinitionFileCommand = RegisterCommand(mcs, PkgCmdIDList.cmdIdAddNewSolutionLicenseHeaderDefinitionFile, AddNewSolutionLicenseHeaderDefinitionFileCallback); _openSolutionHeaderDefinitionFileCommand = RegisterCommand(mcs, PkgCmdIDList.cmdIdOpenSolutionLicenseHeaderDefinitionFile, OpenSolutionLicenseHeaderDefinitionFileCallback); _removeSolutionHeaderDefinitionFileCommand = RegisterCommand(mcs, PkgCmdIDList.cmdIdRemoveSolutionLicenseHeaderDefinitionFile, RemoveSolutionLicenseHeaderDefinitionFileCallback); _addNewSolutionHeaderDefinitionFileCommand.BeforeQueryStatus += QuerySolutionCommandStatus; RegisterCommand(mcs, PkgCmdIDList.cmdIdAddNewLicenseHeaderDefinitionFileToProject, AddNewLicenseHeaderDefinitionFileToProjectCallback); RegisterCommand(mcs, PkgCmdIDList.cmdIdAddExistingLicenseHeaderDefinitionFileToProject, AddExistingLicenseHeaderDefinitionFileToProjectCallback); RegisterCommand(mcs, PkgCmdIDList.cmdIdLicenseHeaderOptions, LicenseHeaderOptionsCallback); RegisterCommand(mcs, PkgCmdIDList.cmdIdAddLicenseHeaderToAllFilesInSolution, buttonHandlerFactory.CreateAddLicenseHeaderToAllProjectsButtonHandler().HandleButton); RegisterCommand(mcs, PkgCmdIDList.cmdIdRemoveLicenseHeaderFromAllFilesInSolution, RemoveLicenseHeaderFromAllFilesInSolutionCallback); } //register ItemAdded event handler var events = _dte.Events as Events2; if (events != null) { _projectItemEvents = events.ProjectItemsEvents; //we need to keep a reference, otherwise the object is garbage collected and the event won't be fired _projectItemEvents.ItemAdded += ItemAdded; //Register to WebsiteItemEvents for Website Projects to work //Reference: https://social.msdn.microsoft.com/Forums/en-US/dde7d858-2440-43f9-bbdc-3e1b815d4d1e/itemadded-itemremoved-and-itemrenamed-events-not-firing-in-web-projects?forum=vsx //Concerns, that the ItemAdded Event gets called on unrelated events, like closing the solution or opening folder, could not be reproduced try { _websiteItemEvents = events.GetObject("WebSiteItemsEvents") as ProjectItemsEvents; } catch (Exception) { //TODO: Add log statement as soon as we have added logging. //This probably only throws an exception if no WebSite component is installed on the machine. //If no WebSite component is installed, they are probably not using a WebSite Project and therefore dont need that feature. } if (_websiteItemEvents != null) { _websiteItemEvents.ItemAdded += ItemAdded; } } //register event handlers for linked commands var page = (OptionsPage)GetDialogPage(typeof(OptionsPage)); if (page != null) { foreach (var command in page.LinkedCommands) { command.Events = _dte.Events.CommandEvents[command.Guid, command.Id]; switch (command.ExecutionTime) { case ExecutionTime.Before: command.Events.BeforeExecute += BeforeLinkedCommandExecuted; break; case ExecutionTime.After: command.Events.AfterExecute += AfterLinkedCommandExecuted; break; } } page.LinkedCommandsChanged += CommandsChanged; //register global event handler for ItemAdded _commandEvents = _dte.Events.CommandEvents; _commandEvents.BeforeExecute += BeforeAnyCommandExecuted; } }
public void init(DTE2 application, ext_ConnectMode connectMode, AddIn addInInstance) { _applicationObject = application; _addInInstance = addInInstance; _connectMode = connectMode; // // Subscribe to solution events. // if(_connectMode != ext_ConnectMode.ext_cm_CommandLine) { _solutionEvents = application.Events.SolutionEvents; _solutionEvents.Opened += new _dispSolutionEvents_OpenedEventHandler(solutionOpened); _solutionEvents.AfterClosing += new _dispSolutionEvents_AfterClosingEventHandler(afterClosing); _solutionEvents.ProjectAdded += new _dispSolutionEvents_ProjectAddedEventHandler(projectAdded); _solutionEvents.ProjectRemoved += new _dispSolutionEvents_ProjectRemovedEventHandler(projectRemoved); _solutionEvents.ProjectRenamed += new _dispSolutionEvents_ProjectRenamedEventHandler(projectRenamed); } _buildEvents = _applicationObject.Events.BuildEvents; _buildEvents.OnBuildBegin += new _dispBuildEvents_OnBuildBeginEventHandler(buildBegin); _buildEvents.OnBuildDone += new _dispBuildEvents_OnBuildDoneEventHandler(buildDone); if(_connectMode != ext_ConnectMode.ext_cm_CommandLine) { beginTrackDocumentEvents(); // // Ensure DEVPATH isn't empty, if there is a project in development mode and DEVPATH is // empty vshosting process will crash. // string devPath = Environment.GetEnvironmentVariable("DEVPATH"); if(String.IsNullOrEmpty(devPath)) { setDotNetDevPath(Util.getIceHome() + "\\bin\\"); } // // Subscribe to command events. // foreach(Command c in _applicationObject.Commands) { if(c.Name.Equals("Project.AddNewItem")) { _addNewItemEvent = application.Events.get_CommandEvents(c.Guid, c.ID); _addNewItemEvent.AfterExecute += new _dispCommandEvents_AfterExecuteEventHandler(afterAddNewItem); } else if(c.Name.Equals("Edit.Remove")) { _editRemoveEvent = application.Events.get_CommandEvents(c.Guid, c.ID); _editRemoveEvent.AfterExecute += new _dispCommandEvents_AfterExecuteEventHandler(editDeleteEvent); } else if(c.Name.Equals("Edit.Delete")) { _editDeleteEvent = application.Events.get_CommandEvents(c.Guid, c.ID); _editDeleteEvent.AfterExecute += new _dispCommandEvents_AfterExecuteEventHandler(editDeleteEvent); } else if(c.Name.Equals("Project.ExcludeFromProject")) { _excludeFromProjectEvent = application.Events.get_CommandEvents(c.Guid, c.ID); _excludeFromProjectEvent.BeforeExecute += new _dispCommandEvents_BeforeExecuteEventHandler(beforeExcludeFromProjectEvent); _excludeFromProjectEvent.AfterExecute += new _dispCommandEvents_AfterExecuteEventHandler(afterExcludeFromProjectEvent); } else if(c.Name.Equals("Project.AddExistingItem")) { _addExistingItemEvent = application.Events.get_CommandEvents(c.Guid, c.ID); _addExistingItemEvent.AfterExecute += new _dispCommandEvents_AfterExecuteEventHandler(afterAddExistingItem); } else if(c.Name.Equals("Build.Cancel")) { _buildCancelEvent = application.Events.get_CommandEvents(c.Guid, c.ID); _buildCancelEvent.AfterExecute += new _dispCommandEvents_AfterExecuteEventHandler(afterBuildCancel); } else if(c.Name.Equals("Debug.Start")) { _debugStartEvent = application.Events.get_CommandEvents(c.Guid, c.ID); _debugStartEvent.BeforeExecute += new _dispCommandEvents_BeforeExecuteEventHandler(setDotNetDebugEnvironment); } else if(c.Name.Equals("Debug.StartWithoutDebugging")) { _debugStartWithoutDebuggingEvent = application.Events.get_CommandEvents(c.Guid, c.ID); _debugStartWithoutDebuggingEvent.BeforeExecute += new _dispCommandEvents_BeforeExecuteEventHandler(setDotNetDebugEnvironment); } else if(c.Name.Equals("ClassViewContextMenus.ClassViewProject.Debug.Startnewinstance")) { _debugStartNewInstance = application.Events.get_CommandEvents(c.Guid, c.ID); _debugStartNewInstance.BeforeExecute += new _dispCommandEvents_BeforeExecuteEventHandler(setDotNetDebugEnvironment); } else if(c.Guid.Equals(Util.refreshCommandGUID) && c.ID == Util.refreshCommandID) { Util.setRefreshCommand(c); } } } _serviceProvider = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)_applicationObject.DTE); initErrorListProvider(); if(connectMode != ext_ConnectMode.ext_cm_CommandLine) { setupCommandBars(); } }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the /// place where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress) { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_OnAssemblyResolve; JoinableTaskFactory = ThreadHelper.JoinableTaskFactory; LicenseHeaderExtractor = new LicenseHeaderExtractor(); await base.InitializeAsync(cancellationToken, progress); await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); Dte2 = await GetServiceAsync(typeof(DTE)) as DTE2; Assumes.Present(Dte2); CreateAndConfigureFileAppender(Path.GetFileNameWithoutExtension(Dte2?.Solution.FullName)); await CreateAndConfigureOutputPaneAppenderAsync(); s_log.Info("Logger has been initialized"); _addedItems = new Stack <ProjectItem>(); await AddHeaderToProjectItemCommand.InitializeAsync(this); await RemoveHeaderFromProjectItemCommand.InitializeAsync(this); await AddLicenseHeaderToAllFilesInSolutionCommand.InitializeAsync(this); await RemoveLicenseHeaderFromAllFilesInSolutionCommand.InitializeAsync(this); await AddNewSolutionLicenseHeaderDefinitionFileCommand.InitializeAsync(this, Dte2?.Solution, () => DefaultLicenseHeaderPageModel.LicenseHeaderFileText); await OpenSolutionLicenseHeaderDefinitionFileCommand.InitializeAsync(this); await RemoveSolutionLicenseHeaderDefinitionFileCommand.InitializeAsync(this); await AddLicenseHeaderToAllFilesInProjectCommand.InitializeAsync(this); await RemoveLicenseHeaderFromAllFilesInProjectCommand.InitializeAsync(this); await AddNewLicenseHeaderDefinitionFileToProjectCommand.InitializeAsync(this); await AddExistingLicenseHeaderDefinitionFileToProjectCommand.InitializeAsync(this); await LicenseHeaderOptionsCommand.InitializeAsync(this); await AddLicenseHeaderToAllFilesInFolderCommand.InitializeAsync(this); await RemoveLicenseHeaderFromAllFilesInFolderCommand.InitializeAsync(this); await AddExistingLicenseHeaderDefinitionFileToFolderCommand.InitializeAsync(this); await AddNewLicenseHeaderDefinitionFileToFolderCommand.InitializeAsync(this); await AddLicenseHeaderEditorAdvancedMenuCommand.InitializeAsync(this); await RemoveLicenseHeaderEditorAdvancedMenuCommand.InitializeAsync(this); //register ItemAdded event handler if (Dte2?.Events is Events2 events) { _projectItemEvents = events.ProjectItemsEvents; //we need to keep a reference, otherwise the object is garbage collected and the event won't be fired _projectItemEvents.ItemAdded += ItemAdded; //Register to WebsiteItemEvents for Website Projects to work //Reference: https://social.msdn.microsoft.com/Forums/en-US/dde7d858-2440-43f9-bbdc-3e1b815d4d1e/itemadded-itemremoved-and-itemrenamed-events-not-firing-in-web-projects?forum=vsx //Concerns, that the ItemAdded Event gets called on unrelated events, like closing the solution or opening folder, could not be reproduced try { _websiteItemEvents = events.GetObject("WebSiteItemsEvents") as ProjectItemsEvents; } catch (Exception ex) { //This probably only throws an exception if no WebSite component is installed on the machine. //If no WebSite component is installed, they are probably not using a WebSite Project and therefore don't need that feature. s_log.Error("No WebSite component is installed on the machine: ", ex); } if (_websiteItemEvents != null) { _websiteItemEvents.ItemAdded += ItemAdded; } } // migrate options from registry to config file await MigrateOptionsAsync(); //register event handlers for linked commands var page = GeneralOptionsPageModel; if (page != null) { foreach (var command in page.LinkedCommands) { command.Events = Dte2.Events.CommandEvents[command.Guid, command.Id]; switch (command.ExecutionTime) { case ExecutionTime.Before: command.Events.BeforeExecute += BeforeLinkedCommandExecuted; break; case ExecutionTime.After: command.Events.AfterExecute += AfterLinkedCommandExecuted; break; default: throw new ArgumentOutOfRangeException(); } } page.LinkedCommandsChanged += CommandsChanged; //register global event handler for ItemAdded _commandEvents = Dte2.Events.CommandEvents; _commandEvents.BeforeExecute += BeforeAnyCommandExecuted; } }