Enable ribbon controls in specific documents C# vsto 2010 - c#

I have an MS Office 2010 application level add-in, when it's loaded all ribbon controls in my custom tab are disabled.Then based on certain conditions I run this method to enable all the ribbon controls in my custom tab:
public void EnableRibbonControls()
{
IUnityContainer container = ServiceLocator.Current.GetInstance<IUnityContainer>();
RibbonTab customTab = container.Resolve<RibbonTab>();
for (int i = 0; i < customTab.Groups.Count; i++)
{
IList<RibbonControl> controls = customTab.Groups[i].Items;
foreach (var control in controls)
{
control.Enabled = true;
}
}
}
The problem is that this code enables the ribbon controls in the ribbon of every open Word document and not the specific one that I'm working on.
I would like to know whether the only way to fix this is by implementing a document level add-in or does someone know a work around for this in the application level add-in?

I currently approach the same problem (in Excel) by setting a GUID as a custom document property and then add an event handler on the Document.Activate event in my application level VSTO add-in. Whenever a document is activated, I check for the GUID and then hide or show the buttons accordingly.
Condensed Code Example:
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
var app = Globals.ThisAddIn.Application;
app.WorkbookActivate += new Excel.AppEvents_WorkbookActivateEventHandler(Application_WorkbookActivate);
app.WorkbookDeactivate += new Excel.AppEvents_WorkbookDeactivateEventHandler(Application_WorkbookDeactivate);
}
private Guid _GetIdentity(Excel.Workbook Wb)
{
try
{
// check for GUID
Microsoft.Office.Core.DocumentProperties properties = Wb.CustomDocumentProperties;
Microsoft.Office.Core.DocumentProperty version = properties["_CustomIdentifier"];
// parse the version for decide what features to activate
Guid guidVersion;
return Guid.TryParse(Convert.ToString(version.Value), out guidVersion) ? guidVersion : Guid.Empty;
}
catch
{
return Guid.Empty;
}
}
void Application_WorkbookDeactivate(Excel.Workbook Wb)
{
Globals.Ribbons.MyRibbon.btnButtonName.Visible = false;
}
void Application_WorkbookActivate(Excel.Workbook Wb)
{
if(_GetIdentity(Wb) == {PRE-DEFINED-GUID})
{
Globals.Ribbons.MyRibbon.btnButtonName.Visible = true;
}
}
My code is specific to Excel, you will need to check the docs what Word equivalent of the Activate/Deactivate events.
Disclaimer: This is only an extract of my actual code, may contain errors.

Related

Display MS Word document in window for editing

 Hello, I am building windows C# WPF application which communicates with Microsoft Office word document (.docx). The app should update .docx template file with user input and this step is achived successfuly using OpenXML. The other part of the app is to show the edited word document to the user inside of the applicaion window or using MS Word and allow him to add some more information if he wants to do it. The problem I am facing is:
I should disable my application controls while word document is opened and I should enable them once the word is closed, also I want to know if the word app was saved (if a user made changes).  The next code is button click event for openning word document:
using System.Windows;
using Microsoft.Office.Interop.Word;
using Application = Microsoft.Office.Interop.Word.Application;
public class MainWindowViewModel : BaseViewModel
{
...
... some view model initialization
...
public bool AreControlsEnabled { get; set; } = true;
private void OpenWord ()
{
AreControlsEnabled = false;
var app = new Application()
{
Visible = true
};
var doc = app.Documents.Open("pathtofile.docx");
var docClass = app.ActiveDocument as DocumentClass;
docClass.DocumentEvents2_Event_Close += DocClass_DocumentEvents2_Event_Close;
docClass.DocumentEvents_Event_Close += DocClass_DocumentEvents_Event_Close;
app.DocumentBeforeClose += new ApplicationEvents4_DocumentBeforeCloseEventHandler(DocBeforeClose);
app.DocumentBeforeSave += new ApplicationEvents4_DocumentBeforeSaveEventHandler(DocBeforeSave);
}
private void DocClass_DocumentEvents2_Event_Close ()
{
MessageBox.Show("DocClass_DocumentEvents2_Event_Close");
AreControlsEnabled = true;
}
private void DocClass_DocumentEvents_Event_Close ()
{
MessageBox.Show("DocClass_DocumentEvents_Event_Close");
AreControlsEnabled = true;
}
private void DocBeforeClose (Document doc, ref bool cancel)
{
MessageBox.Show("DocBeforeClose");
AreControlsEnabled = true;
}
private void DocBeforeSave (Document doc, ref bool SaveAsUI, ref bool cancel)
{
MessageBox.Show("DocBeforeSave");
AreControlsEnabled = true;
}
}
 When I run the code - I see opened MS Word document as expected, but when I close it or save - no one of events fired and I can't understand why. Also, I can use System.Diagnostics.Process to launch the Word and add exit event to it, but in this way I can't know if the user applied some changes. So, if someone solved this problem, help me please.   Thank you for reading and answers
You can:
Get the Current Changed Date of the File
Use System.Diagnostics.Process to start Word.
After The process ends you check the Changed Date again
If the user saved the file the Changed Date is updated
I don't know if the process is still running if the user just closes the document but not word. For this you could observe the Folder of the Dokument for thos ~... Temp Files Word creates while a document is open...

In a VSTO MS Word add-in, a Ribbon Toggle button clicked in one document causes it to be clicked in other running instances of MS Word

I have developed a MS Word add-in and it has several buttons in the ribbon menu. The first button is a Toggle button and clicking it causes a task pane to load. The problem I have been experiencing is that if I have multiple instances of MS Word open and I click this toggle button in one of the instances, it automatically appears clicked in the other running instances of MS Word as well but the task pane appears to be loaded only in the instance where I had clicked the toggle button. I would like the toggle button to work independently in every instance of MS Word. I have tried several ways of doing this but haven't found a solution yet. I have experienced the same behavior for another add-in that I developed for MS PowerPoint.
Any help in this matter will be appreciated.
I have a ribbon designer (named rbcOfficeAddin) added to my add-in project and it has a toggle button named btnTaskPane. Below is the code:
public partial class rbcOfficeAddin
{
private void btnTaskPane_Click(object sender, RibbonControlEventArgs e)
{
if (this.btnTaskPane.Checked)
{ this.btnTaskPane.Label = "Hide Task Pane"; }
else { this.btnTaskPane.Label = "Show Hide Pane"; }
Globals.ThisAddIn.ShowHideActionPane(this.btnTaskPane.Checked);
}
}
The click handler of toggle button calls a method of ThisAddin as shown below:
public partial class ThisAddIn
{
private bool operationsPaneCreated = false;
public void ShowHideActionPane(bool flag)
{
try
{
if (!this.operationsPaneCreated)
{
this.CreateTaskPane();
this.operationsPaneCreated = true;
}
myCustomTaskPane.Visible = flag;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void CreateTaskPane()
{
//OperationsPane is a user control
oOperationsPane = new OperationsPane();
myCustomTaskPane = this.CustomTaskPanes.Add(oOperationsPane,
"Operations Pane");
myCustomTaskPane.DockPosition =
Office.MsoCTPDockPosition.msoCTPDockPositionFloating;
myCustomTaskPane.Height = 500;
myCustomTaskPane.Width = oOperationsPane.Width;
myCustomTaskPane.DockPosition =
Office.MsoCTPDockPosition.msoCTPDockPositionRight;
myCustomTaskPane.Width = 420;
myCustomTaskPane.Control.AutoScroll = true;
myCustomTaskPane.Visible = false;
myCustomTaskPane.VisibleChanged += myCustomTaskPane_VisibleChanged;
}
void myCustomTaskPane_VisibleChanged(object sender, EventArgs e)
{
try
{
if (!myCustomTaskPane.Visible && Globals.Ribbons.rbcOfficeAddin.btnTaskPane.Checked)
{
Globals.Ribbons.rbcOfficeAddin.btnTaskPane.Checked = false;
Globals.Ribbons.rbcOfficeAddin.btnTaskPane.Label = "Show Task Pane";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
This same question was asked and answered on the MSDN forums. I'm copying/pasting the relevant information here, with attributions, from
https://social.msdn.microsoft.com/Forums/vstudio/en-US/1c3cab02-b231-4453-ae09-325e025606bf/in-a-vsto-ms-word-addin-a-ribbon-toggle-button-clicked-in-one-document-causes-it-to-be-clicked-in?forum=vsto
Answer from Starain chen Microsoft contingent staff, Moderator:
As far as I know, this is by design, for an instance with multiple
word documents, the same add-in will be in a domain, for example, a
variable is changed will be affect other word documents if they are in
the same instance. So, you need to deal with this scenario. (e.g. base
on document name)
Answer from Cindy Meister, MVP, Moderator:
The following article explains the approach. It's valid for Ribbon
customizations as well as just Custom Task Panes
https://msdn.microsoft.com/en-us/library/vstudio/bb608620

Change App language at RunTime on-the-fly

I'm currently developing a metro app in which the user can change current language at runtime and all the custom controls that are loaded must update their text regarding to the new language. Problem is that when I change the language using the following code, the app language changes but it will only update text when I restart my app because the pages and controls that are already rendered are cached.
LocalizationManager.UICulture = new System.Globalization.CultureInfo((string)((ComboBoxItem)e.AddedItems[0]).Tag);
Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = ((ComboBoxItem)e.AddedItems[0]).Tag as String;
What should I do to force updating text of all custom controls at runtime without restarting my app?
Use this:
var NewLanguage = (string)((ComboBoxItem)e.AddedItems[0]).Tag;
Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = NewLanguage;
Windows.ApplicationModel.Resources.Core.ResourceContext.GetForViewIndependentUse().Reset();
//Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().Reset();
Windows.ApplicationModel.Resources.Core.ResourceManager.Current.DefaultContext.Reset();
and then reload your Page, using Navigate method:
if (Frame != null)
Frame.Navigate(typeof(MyPage));
In order to respond right away, you would need to reset the context of the resource manager.
For Windows 8.1:
var resourceContext = Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView();
resourceContext.Reset();
You will still need to force your page to redraw itself and thus re-request the resources to get the changes to take place. For Windows 8, you can see https://timheuer.com/blog/archive/2013/03/26/howto-refresh-languages-winrt-xaml-windows-store.aspx
You can change the app's language at runtime with the help of this source code. I took help from this and manipulated my app's language settings page as follows:
In languageSettings.xaml.cs:
public partial class LanguageSettings : PhoneApplicationPage
{
public LanguageSettings()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (ChangeLanguageCombo.Items.Count == 0)
{ ChangeLanguageCombo.Items.Add(LocalizationManager.SupportedLanguages.En);
ChangeLanguageCombo.Items.Add(LocalizationManager.SupportedLanguages.Bn);
}
SelectChoice();
}
private void ButtonSaveLang_OnClick(object sender, RoutedEventArgs e)
{
//Store the Messagebox result in result variable
MessageBoxResult result = MessageBox.Show("App language will be changed. Do you want to continue?", "Apply Changes", MessageBoxButton.OKCancel);
//check if user clicked on ok
if (result == MessageBoxResult.OK)
{
var languageComboBox = ChangeLanguageCombo.SelectedItem;
LocalizationManager.ChangeAppLanguage(languageComboBox.ToString());
//Application.Current.Terminate(); I am commenting out because I don't neede to restart my app anymore.
}
else
{
SelectChoice();
}
}
private void SelectChoice()
{
//Select the saved language
string lang = LocalizationManager.GetCurrentAppLang();
if(lang == "bn-BD")
ChangeLanguageCombo.SelectedItem = ChangeLanguageCombo.Items[1];
else
{
ChangeLanguageCombo.SelectedItem = ChangeLanguageCombo.Items[0];
}
}
}
***Note: Before understanding what I did on LanguageSettings page's code behind, you must implement the codes from the link as stated earlier. And also it may be noted that I am working on windows phone 8

HelpFile contents are not opened

I have an applications that install two other application which has a "Help" option. Each of these application has a common help file but the contents should be displayed based on the index selected for the application in the "Table of Contents". If i open one application, the help of that particular application should be displayed.
My code looks like this for Appl1.
private void Help_Click(Core.CommandBarButton Ctrl, ref bool CancelDefault)
{
if (System.IO.File.Exists(new PlugInConstants().HELP_FILE_Path))
{
System.Windows.Forms.Help.ShowHelp(new System.Windows.Forms.Control(),
new PlugInConstants().HELP_FILE_Path,
System.Windows.Forms.HelpNavigator.TableOfContents, "Appl1");
}
else
{
System.Windows.Forms.MessageBox.Show(m_objLanguage.ERR_HELP_NOT_FOUND.Replace
("%1", m_objGlobalConfig.HelpFilename));
}
CancelDefault = false;
}
and looks like this for Appl2
private void HelpToolStripMenuItem_Click(object sender, EventArgs e)
{
helpToolStripMenuItem.Enabled = false;
string helpFilePath;
helpFilePath = new TrayConstants().HELP_FILE_Path;
if (System.IO.File.Exists(helpFilePath))
{
System.Windows.Forms.Help.ShowHelp(new System.Windows.Forms.Control(),
helpFilePath, System.Windows.Forms.HelpNavigator.TableOfContents, "Appl2") ;
}
else
{
if (m_helpPage == null)
m_helpPage = new HelpPage();
m_helpPage.ShowDialog();
}
helpToolStripMenuItem.Enabled = true;
}
from this i can only see the Content page of common helpfile, but not the particular application help that is selected.
Now i did run Appl1 but still i can see the main MyAppbut not Appl1that is automatically selected and the contents that is displayed to right.
I am using VS 2010,C#, win forms
thanks in advance
I believe that your issue is that you are accessing the wrong value in the HelpNavigator enum. Looks like it should be Topic, not TableOfContents.
System.Windows.Forms.Help.ShowHelp(new System.Windows.Forms.Control(),
helpFilePath, System.Windows.Forms.HelpNavigator.Topic, "Appl2") ;
http://msdn.microsoft.com/en-us/library/system.windows.forms.helpnavigator.aspx

A Possible Threading/COM/UI problem

I am writing a toolbar for IE(6+). I have used the various sample bars from
codeproject.com (http://www.codeproject.com/KB/dotnet/IE_toolbar.aspx), and have a toolbar that works, registers unregisters etc. What I want the toolbar to do is to highlight divs within an html page as the users' mouse moves over that div. So far the highlighting code works, but I would like to display the name of the div (if it exists) in a label on the toolbar (changing as the mouse moves etc).
I cannot for the life of me get this to happen and trying to debug it is a nightmare. As the assembly is hosted in IE, I suspect that I am causing an exception (in IE) by trying to update the text on the label from a thread that didn't create that control, but because that exception is happening in IE, I don't see it.
Is the solution to try to update the control in a thread-safe way using Invoke? If so how?
Here is the event code:
private void Explorer_MouseOverEvent(mshtml.IHTMLEventObj e)
{
mshtml.IHTMLDocument2 doc = this.Explorer.Document as IHTMLDocument2;
element = doc.elementFromPoint(e.clientX, e.clientY);
if (element.tagName.Equals("DIV", StringComparison.InvariantCultureIgnoreCase))
{
element.style.border = "thin solid blue;";
if (element.className != null)
{
UpdateToolstrip(element.className);
}
}
e.returnValue = false;
}
and here is an attempt at thread-safe update of the toolbar:
delegate void UpdateToolstripDelegate(string text);
public void UpdateToolstrip(string text)
{
if (this.toolStripLabel1.InvokeRequired == false)
{
this.toolStripLabel1.Text = text;
}
else
{
this.Invoke(new UpdateToolstripDelegate(UpdateToolstrip), new object[] { text });
}
}
Any suggestions much appreciated.
I can't really reproduce the issue (creating a test project for an IE toolbar is a tad too much work), but you can try this:
Add the following routine to a public static (extensions methods) class:
public static void Invoke(this Control control, MethodInvoker methodInvoker)
{
if (control.InvokeRequired)
control.Invoke(methodInvoker);
else
methodInvoker();
}
And then replace the section of similar code in the first block with this:
if (element.className != null)
{
this.Invoke(() => toolStripLabel1.Text = element.className);
}
This is a sure-fire way of avoiding thread-safe issues in UI applications.

Categories

Resources