VSTO 2005 COM Add-In Word Buttons not responding after first click

K

Kevin Gordon

The COM Add-In (code below) runs fine but only for one button click. Either
button runs only once then both "Check In" and "Check Out" will not respond
to a second click. Any comments welcome. Thanks, Kevin Gordon.



namespace DocumentAddin

{

using System;

using Extensibility;

using System.Runtime.InteropServices;

using System.Reflection;

using System.Resources;

using System.Drawing;

using Microsoft.Office.Core;

using System.Windows.Forms;

using Microsoft.Office.Tools;

using Word = Microsoft.Office.Interop.Word;

#region Read me for Add-in installation and setup information.

// When run, the Add-in wizard prepared the registry for the Add-in.

// At a later time, if the Add-in becomes unavailable for reasons such as:

// 1) You moved this project to a computer other than which is was
originally created on.

// 2) You chose 'Yes' when presented with a message asking if you wish to
remove the Add-in.

// 3) Registry corruption.

// you will need to re-register the Add-in by building the
DocumentAddinSetup project,

// right click the project in the Solution Explorer, then choose install.

#endregion


/// <summary>

/// The object for implementing an Add-in.

/// </summary>

/// <seealso class='IDTExtensibility2' />

[GuidAttribute("CA82E6D6-3E2C-41D3-98D9-DF52276C8110"),
ProgId("DocumentAddin.Connect")]

public class Connect : Object, Extensibility.IDTExtensibility2

{

private Microsoft.Office.Interop.Word.Application applicationObject;

private Microsoft.Office.Core.COMAddIn addInInstance;

private CommandBarButton inButton;

private CommandBarButton outButton;

private object missing = System.Reflection.Missing.Value;

/// <summary>

/// Implements the constructor for the Add-in object.

/// Place your initialization code within this method.

/// </summary>

public Connect()

{

MessageBox.Show("constructor connection");

}

/// <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, Extensibility.ext_ConnectMode
connectMode, object addInInst, ref System.Array custom)

{

applicationObject = (Microsoft.Office.Interop.Word.Application)application;

addInInstance = (Microsoft.Office.Core.COMAddIn)addInInst;

MessageBox.Show("onconnection");

if (connectMode != Extensibility.ext_ConnectMode.ext_cm_Startup)

{

OnStartupComplete(ref custom);

}

}

/// <summary>

/// Implements the OnDisconnection method of the IDTExtensibility2 interface.

/// Receives notification that the Add-in is being unloaded.

/// </summary>

/// <param term='disconnectMode'>

/// Describes how the Add-in is being unloaded.

/// </param>

/// <param term='custom'>

/// Array of parameters that are host application specific.

/// </param>

/// <seealso class='IDTExtensibility2' />

public void OnDisconnection(Extensibility.ext_DisconnectMode disconnectMode,
ref System.Array custom)

{

MessageBox.Show("ondisconnection");

}

/// <summary>

/// Implements the OnAddInsUpdate method of the IDTExtensibility2 interface.

/// Receives notification that the collection of Add-ins has changed.

/// </summary>

/// <param term='custom'>

/// Array of parameters that are host application specific.

/// </param>

/// <seealso class='IDTExtensibility2' />

public void OnAddInsUpdate(ref System.Array custom)

{

MessageBox.Show("onaddinsupdate");

}

/// <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 System.Array custom)

{

object missing = System.Reflection.Missing.Value;

CommandBars commandBars;

CommandBar standardBar;

commandBars = applicationObject.CommandBars;

// Get the standard CommandBar from Word

standardBar = commandBars["Standard"];

try

{

// try to reuse the button is hasn't already been deleted

inButton = (CommandBarButton)standardBar.Controls["Check In"];

//object Temporary = true;

//inButton.Delete(Temporary);

//inButton = (CommandBarButton)standardBar.Controls["Check In"];

}

catch (System.Exception)

{

// If it's not there add a new button

object Before = 1;

inButton =
(CommandBarButton)standardBar.Controls.Add(MsoControlType.msoControlButton,
missing, missing, Before, missing);

inButton.Caption = "Check In";

inButton.Style = MsoButtonStyle.msoButtonIconAndCaptionBelow;

System.Drawing.Icon res;

res = DocumentAddin.Properties.Resources.DME;

Bitmap bmp;

bmp = res.ToBitmap();

Clipboard.SetDataObject(bmp, true);

inButton.FaceId = 0;

inButton.PasteFace();

}

try

{

// try to reuse the button is hasn't already been deleted

outButton = (CommandBarButton)standardBar.Controls["Check Out"];

//object Temporary = false;

//outButton.Delete(Temporary);

//outButton = (CommandBarButton)standardBar.Controls["Check Out"];

}

catch (System.Exception)

{

// If it's not there add a new button

object Before = 1;

outButton =
(CommandBarButton)standardBar.Controls.Add(MsoControlType.msoControlButton,
missing, missing, Before, missing);

outButton.Caption = "Check Out";

outButton.Style = MsoButtonStyle.msoButtonIconAndCaptionBelow;

System.Drawing.Icon res2;

res2 = DocumentAddin.Properties.Resources.DME2;

Bitmap bmp2;

bmp2 = res2.ToBitmap();

Clipboard.SetDataObject(bmp2, true);

outButton.FaceId = 0;

outButton.PasteFace();

}

// Make sure the button is visible

inButton.OnAction = "!<DocumentAddin.Connect>";

inButton.Visible = true;

inButton.Click += new
_CommandBarButtonEvents_ClickEventHandler(inButton_Click);

outButton.OnAction = "!<DocumentAddin.Connect>";

outButton.Visible = true;

outButton.Click += new
_CommandBarButtonEvents_ClickEventHandler(outButton_Click);

standardBar = null;

commandBars = null;

//ApplicationClass app = applicationObject as ApplicationClass;

//app.ApplicationEvents3_Event_DocumentOpen += new
ApplicationEvents3_DocumentOpenEventHandler(Event_DocumentOpen);

}

/// <summary>

/// Implements the OnBeginShutdown method of the IDTExtensibility2 interface.

/// Receives notification that the host application is being unloaded.

/// </summary>

/// <param term='custom'>

/// Array of parameters that are host application specific.

/// </param>

/// <seealso class='IDTExtensibility2' />

public void OnBeginShutdown(ref System.Array custom)

{

//MessageBox.Show("onbeginshutdown");

}


void inButton_Click(CommandBarButton ctrl, ref bool cancelDefault)

{

Object oMissing = Type.Missing;

object missing = System.Reflection.Missing.Value;

DME.Session objSession;

DME.Document objDocument;

DME.Fields objFields;

DME.Field objField;

DME.dmeObjectClass enumClassType;

DME.Search objSearch;

DME.SearchResults objSearchResults;

DocumentAddin.SaveForm oForm;

string sDocumentID = null;

string sDocIDs;

string sDocumentName = null;

string sFilename;

string sReference;

string sPath = @"C:\DME";

try

{

if (!System.IO.Directory.Exists(sPath))

{

System.IO.Directory.CreateDirectory(sPath);

}

oForm = new SaveForm();

oForm.labelAuthor.Visible = false;

oForm.labelDocExtension.Visible = false;

oForm.labelDocID.Visible = false;

oForm.labelDocName.Visible = false;

oForm.labelDocStatus.Visible = false;

oForm.labelDocType.Visible = false;

oForm.labelPermanent.Visible = false;

oForm.labelSmartFolder.Visible = false;

oForm.txtDocID.Visible = false;

oForm.txtDocID.Enabled = false;

oForm.txtAuthor.Visible = false;

oForm.txtAuthor.Enabled = false;

oForm.txtDocExtension.Visible = false;

oForm.txtDocExtension.Enabled = false;

oForm.txtDocName.Visible = false;

oForm.txtDocName.Enabled = false;

oForm.txtDocStatus.Visible = false;

oForm.txtDocStatus.Enabled = false;

oForm.txtDocType.Visible = false;

oForm.txtDocType.Enabled = false;

oForm.txtPermanent.Visible = false;

oForm.txtPermanent.Enabled = false;

oForm.txtSmartFolder.Visible = false;

oForm.txtSmartFolder.Enabled = false;

objSession = new DME.Session();

objSearch = objSession.Hierarchy.CreateSearch();

objSearch.Depth = -1;

objSearch.Columns.Add(DME.dmePropIDs.DmePR_CREATED_AT);

object vntValue = 2;

objSearch.Criterions.AddComparison(DME.dmePropIDs.DmePR_LOCK_STATE,
DME.dmeSearchOperatorType.soEquals, vntValue);

objSearch.Execute(@"\\IS\CORE Documentation\", null, true, false);

if (objSearch.Status == DME.dmeSearchStatus.dmessComplete)

{

oForm.DMEListView.View = View.Details;

oForm.DMEListView.LabelEdit = false;

oForm.DMEListView.Sorting = SortOrder.Ascending;

oForm.DMEListView.GridLines = true;

oForm.DMEListView.FullRowSelect = true;

oForm.DMEListView.Columns.Add("ID", 60, HorizontalAlignment.Left);

oForm.DMEListView.Columns.Add("Name", 205, HorizontalAlignment.Left);

oForm.DMEListView.Columns.Add("State", 95, HorizontalAlignment.Left);

oForm.DMEListView.Columns.Add("Dated", 85, HorizontalAlignment.Left);

objSearchResults = objSearch.SearchResults;

foreach (DME.SearchResult objSearchResult in objSearchResults)

{

ListViewItem DMEListItem = new ListViewItem(objSearchResult.DocumentID);

DMEListItem.SubItems.Add(objSearchResult.Name);

if ((int)objSearchResult.Fields[DME.dmePropIDs.DmePR_LOCK_STATE].Value == 0)

{

DMEListItem.SubItems.Add("Available");

}

if ((int)objSearchResult.Fields[DME.dmePropIDs.DmePR_LOCK_STATE].Value == 1)

{

DMEListItem.SubItems.Add("Opened");

}

if ((int)objSearchResult.Fields[DME.dmePropIDs.DmePR_LOCK_STATE].Value == 2)

{

DMEListItem.SubItems.Add("CheckedOut");

}

if ((int)objSearchResult.Fields[DME.dmePropIDs.DmePR_LOCK_STATE].Value == 3)

{

DMEListItem.SubItems.Add("System");

}

if ((bool)objSearchResult.Fields[DME.dmePropIDs.DmePR_IS_FOLDER].Value ==
true)

{

DMEListItem.SubItems.Add("Folder");

}

if ((bool)objSearchResult.Fields[DME.dmePropIDs.DmePR_IS_DELETED].Value ==
true)

{

DMEListItem.SubItems.Add("Deleted");

}

DateTime dateCreated =
(DateTime)objSearchResult.Fields[DME.dmePropIDs.DmePR_CREATED_AT].Value;

string sDate = dateCreated.ToShortDateString();

DMEListItem.SubItems.Add(sDate);

if (DMEListItem.Index == 1)

{

DMEListItem.Selected = false;

}

oForm.DMEListView.Items.Add(DMEListItem);

}

oForm.DMEListView.Visible = true;

oForm.ShowDialog();

if (oForm.OkFlag == true && oForm.DMEListView.SelectedItems != null)

{

sDocumentID = oForm.txtDocID.Text;

sDocIDs = sDocumentID;

sDocumentName = oForm.txtDocName.Text;

}

else

{

return;

}

}

enumClassType = objSession.GetObjectClassFromID(sDocumentID);

if ((sDocumentName != null && sDocumentName.Length > 0) && (sDocumentID !=
null && sDocumentID.Length > 0) && (enumClassType ==
DME.dmeObjectClass.dmDocument))

{

objDocument = objSession.GetDocument(sDocumentID);

if (objDocument != null && (long)objDocument.EffectiveAccessMask !=
(long)DME.dmeAccessLevel.dmReadOnly)

{

sReference =
objDocument.Fields[DME.dmePropIDs.DmePR_REFERENCE].Value.ToString();

}

else

{

string sMessage = "Document " + sDocumentID + " was not found or determined
to be marked for deletion.";

MessageBox.Show(sMessage, "Search Failed", MessageBoxButtons.OK);

return;

}

}

else

{

MessageBox.Show("Document ID not properly selected or was an incorrect
type.", "Error", MessageBoxButtons.OK);

return;

}

if (sReference.Substring(0, 4) == "CORE")

{

sFilename = sDocumentID + " " + sDocumentName + ".doc";

Object index = 1;

if (applicationObject.Documents.get_Item(ref index).Name == sFilename)

{

Object file = sFilename;

applicationObject.Documents.get_Item(ref file).Save();

}

else

{

Object noPrompt = false;

Object originalFormat = Type.Missing;

applicationObject.Documents.Save(ref noPrompt, ref originalFormat);

}

objFields = null;

objFields = objDocument.Fields;

objField = objFields.Add(DME.dmePropIDs.DmePR_AUTHOR, oForm.txtAuthor.Text);

objField = objFields.Add(DME.dmePropIDs.DmePR_NAME, oForm.txtDocName.Text);

objField = objFields.Add(DME.dmePropIDs.DmePR_DOCTYPE, oForm.txtDocType.Text);

objField = objFields.Add(DME.dmePropIDs.DmePR_DOC_STATUS,
oForm.txtDocStatus.Text);

//objField = objFields.Add(DME.dmePropIDs.DmePR_DOCID, oForm.txtDocID.Text);
//read-only

objField = objFields.Add(DME.dmePropIDs.DmePR_EXTENSION,
oForm.txtDocExtension.Text);

//objField = objFields.Add(DME.dmePropIDs.DmePR_FOLDER_PATH,
oForm.txtSmartFolder.Text); //read-only

objDocument.CopyFields(objFields);

sFilename = null;

sFilename = "C:\\DME\\" + sDocumentID + " " + oForm.txtDocName.Text +
oForm.txtDocExtension.Text;

string sComment = "Revised by: " + oForm.txtAuthor.Text;

string sMessage;

int lFlag = 96;

objDocument.CheckIn(ref lFlag, sFilename, sComment);

sMessage = sFilename + " has been deleted and Checked In to Document
Management.";

MessageBox.Show(sMessage, "Saved", MessageBoxButtons.OK);

}

}

catch (Exception e)

{

string sMessage = "Error: " + e.Message + " : " + e.Source + "\n";

MessageBox.Show(sMessage, "Exception");

}

finally

{

objSession = null;

objDocument = null;

objSearch = null;

objSearchResults = null;

objFields = null;

objField = null;

sDocumentID = null;

sDocIDs = null;

sDocumentName = null;

sFilename = null;

sReference = null;

}

}

void outButton_Click(CommandBarButton ctrl, ref bool cancelDefault)

{

Object oMissing = Type.Missing;

object missing = System.Reflection.Missing.Value;

DME.Session objSession;

DME.Document objDocument;

DME.dmeObjectClass enumClassType;

DME.Search objSearch;

DME.SearchResults objSearchResults;

DocumentAddin.OpenForm oForm;

string sDocumentID = null;

string sDocIDs;

string sDocumentName;

string sFilename;

string sReference;

string sPath = @"C:\DME";

try

{

if (!System.IO.Directory.Exists(sPath))

{

System.IO.Directory.CreateDirectory(sPath);

}

objSession = new DME.Session();

oForm = new OpenForm();

oForm.cmdOK.Text = "Search";

oForm.DMEListView.Visible = false;

oForm.ClientSize = new System.Drawing.Size(494, 85);

oForm.ShowDialog();

if (oForm.OkFlag == true)

{

sDocumentID = oForm.txtDocID.Text;

sDocIDs = sDocumentID;

sDocumentName = oForm.txtDocName.Text;

if (sDocumentID.Length == 0 && sDocumentName.Length != 0)

{

objSearch = objSession.Hierarchy.CreateSearch();

objSearch.Depth = -1;

objSearch.Columns.Add(DME.dmePropIDs.DmePR_CREATED_AT);

objSearch.Criterions.AddComparison(DME.dmePropIDs.DmePR_NAME,
DME.dmeSearchOperatorType.soContains, sDocumentName);

objSearch.Execute(@"\\IS\CORE Documentation\", null, true, false);

if (objSearch.Status == DME.dmeSearchStatus.dmessComplete)

{

oForm.DMEListView.View = View.Details;

oForm.DMEListView.LabelEdit = false;

oForm.DMEListView.Sorting = SortOrder.Ascending;

oForm.DMEListView.GridLines = true;

oForm.DMEListView.FullRowSelect = true;

oForm.DMEListView.Columns.Add("ID", 60, HorizontalAlignment.Left);

oForm.DMEListView.Columns.Add("Name", 205, HorizontalAlignment.Left);

oForm.DMEListView.Columns.Add("State", 95, HorizontalAlignment.Left);

oForm.DMEListView.Columns.Add("Dated", 85, HorizontalAlignment.Left);

objSearchResults = objSearch.SearchResults;

foreach (DME.SearchResult objSearchResult in objSearchResults)

{

ListViewItem DMEListItem = new ListViewItem(objSearchResult.DocumentID);

DMEListItem.SubItems.Add(objSearchResult.Name);

if ((int)objSearchResult.Fields[DME.dmePropIDs.DmePR_LOCK_STATE].Value == 0)

{

DMEListItem.SubItems.Add("Available");

}

if ((int)objSearchResult.Fields[DME.dmePropIDs.DmePR_LOCK_STATE].Value == 1)

{

DMEListItem.SubItems.Add("Opened");

}

if ((int)objSearchResult.Fields[DME.dmePropIDs.DmePR_LOCK_STATE].Value == 2)

{

DMEListItem.SubItems.Add("CheckedOut");

}

if ((int)objSearchResult.Fields[DME.dmePropIDs.DmePR_LOCK_STATE].Value == 3)

{

DMEListItem.SubItems.Add("System");

}

if ((bool)objSearchResult.Fields[DME.dmePropIDs.DmePR_IS_FOLDER].Value ==
true)

{

DMEListItem.SubItems.Add("Folder");

}

if ((bool)objSearchResult.Fields[DME.dmePropIDs.DmePR_IS_DELETED].Value ==
true)

{

DMEListItem.SubItems.Add("Deleted");

}

DateTime dateCreated =
(DateTime)objSearchResult.Fields[DME.dmePropIDs.DmePR_CREATED_AT].Value;

string sDate = dateCreated.ToShortDateString();

DMEListItem.SubItems.Add(sDate);

if (DMEListItem.Index == 1)

{

DMEListItem.Selected = false;

}

oForm.DMEListView.Items.Add(DMEListItem);

}

oForm.ClientSize = new System.Drawing.Size(494, 305);

oForm.cmdOK.Text = "Selected";

oForm.DMEListView.Visible = true;

oForm.ShowDialog();

if (oForm.OkFlag == true && oForm.DMEListView.SelectedItems != null)

{

sDocumentID = oForm.DMEListView.SelectedItems[0].Text;

sDocIDs = sDocumentID;

}

else

{

return;

}

}

}

}

enumClassType = objSession.GetObjectClassFromID(sDocumentID);

if ((sDocumentID != null && sDocumentID.Length > 0) && (enumClassType ==
DME.dmeObjectClass.dmDocument))

{

objDocument = objSession.GetDocument(sDocumentID);

if (objDocument != null && (long)objDocument.EffectiveAccessMask !=
(long)DME.dmeAccessLevel.dmReadOnly)

{

sReference =
objDocument.Fields[DME.dmePropIDs.DmePR_REFERENCE].Value.ToString();

}

else

{

string sMessage = "Document " + sDocumentID + " was not found or determined
to be marked for deletion.";

MessageBox.Show(sMessage, "Search Failed", MessageBoxButtons.OK);

return;

}

}

else

{

MessageBox.Show("Document ID not entered or ID entered was an incorrect
type.", "Error", MessageBoxButtons.OK);

return;

}

if (sReference.Substring(0, 4) == "CORE")

{

sFilename = objDocument.CheckOut(128, @sPath);

if (sFilename != null && sFilename.Length != 0)

{

MessageBox.Show("Your file has been checked out and saved to: " + sFilename,
"CORE DOCUMENT", MessageBoxButtons.OK);

Object filename = @sFilename;

Object confirmConversions = Type.Missing;

Object readOnly = Type.Missing;

Object addToRecentFiles = Type.Missing;

Object passwordDocument = Type.Missing;

Object passwordTemplate = Type.Missing;

Object revert = Type.Missing;

Object writePasswordDocument = Type.Missing;

Object writePasswordTemplate = Type.Missing;

Object format = Type.Missing;

Object encoding = Type.Missing;

Object visible = Type.Missing;

Object openConflictDocument = Type.Missing;

Object openAndRepair = Type.Missing;

Object documentDirection = Type.Missing;

Object noEncodingDialog = Type.Missing;

Object index = 1;

if (applicationObject.Documents.get_Item(ref index).Name == "Document1")

{

Object saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges;

Object originalFormat = Type.Missing;

Object routeDocument = Type.Missing;

applicationObject.Documents.get_Item(ref index).Close(ref saveChanges, ref
originalFormat, ref routeDocument);

}

applicationObject.Documents.Open(ref filename,

ref confirmConversions, ref readOnly, ref addToRecentFiles,

ref passwordDocument, ref passwordTemplate, ref revert,

ref writePasswordDocument, ref writePasswordTemplate,

ref format, ref encoding, ref visible, ref openConflictDocument,

ref openAndRepair, ref documentDirection, ref noEncodingDialog);

applicationObject.Visible = true;

}

else

{

MessageBox.Show("Document " + sFilename + " not Checked Out!", "Error",
MessageBoxButtons.OK);

}

}

}

catch (Exception e)

{

string sMessage = "Error: " + e.Message + " : " + e.Source + "\n";

MessageBox.Show(sMessage, "Exception");

}

finally

{

objSession = null;

objDocument = null;

objSearch = null;

objSearchResults = null;

sDocumentID = null;

sDocIDs = null;

sDocumentName = null;

sFilename = null;

sReference = null;

}

}

}

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top