I am doing an application in which when I launch a MS Word app,
a button is created and when the MS Word app is closed the button is removed.
So here is what I did to associate the MS Word and the button...
Word.Application wdApp = new Word.Application();
string oldCaption = wdApp.Application.Caption ;
string guid = Guid.NewGuid().ToString();
//set caption to random value
wdApp.Application.Caption = guid;
//make sure app is visible:
wdApp.Visible = true;
//find random value to get process id
int processId = GetProcessIdByWindowTitle(guid);
//reset caption
wdApp.Application.Caption = oldCaption;
//create a dictionary
Dictionary<int, Button> mapping = new Dictionary<int, button>();
//add mapping
mapping.Add(new KeyValuePair<int, Button>(processId, deleteButton));
public static int GetProcessIdByWindowTitle(string AppId)
{
Process[] P_CESSES = Process.GetProcesses();
for (int p_count = 0; p_count < P_CESSES.Length; p_count++)
{
if (P_CESSES[p_count].MainWindowTitle.Equals(AppId))
{
return P_CESSES[p_count].Id;
}
}
return Int32.MaxValue;
}
But I got an error here mapping.Add(new KeyValuePair<int, Button>(processId, deleteButton));
I am getting this error: “No overload method for Add takes 1 argument”...
What should I do ?
Is there any oher solution for this ?
Thank you.
EDIT :
I have modified my code but I can remove only the last button that I created, when I want to remove the others I can't... I put breakpoint in order to know the value of the different variables.
But when I create 2 buttons, the count in the mapping.add is always equal to 1... Is it normal ?
here is the code:
try
{
Word.Application wdApp = new Word.Application();
string oldCaption = wdApp.Application.Caption;
string guid = Guid.NewGuid().ToString();
//set caption to random value
wdApp.Application.Caption = guid;
//make sure app is visible:
wdApp.Visible = true;
//find random value to get process id
int processId = GetProcessIdByWindowTitle(guid);
//reset caption
wdApp.Application.Caption = oldCaption;
if( wdApp.Visible == true)
{
deleteButton = new Microsoft.Office.Tools.Word.Controls.Button();
//create a dictionary
mapping = new Dictionary<int, Button>();
//add mapping
mapping.Add(processId, deleteButton);
PIC_Barre.Controls.Add(deleteButton);
//PIC_Barre.Controls.Add(_button);
}
((Word.ApplicationEvents4_Event)wdApp).Quit += () =>
{
// remove the button corresponding to the processid
var method = (Action)(() =>
PIC_Barre.Controls.Remove(mapping[processId]));
if (mapping[processId].InvokeRequired)
{
mapping[processId].Invoke(method);
}
// remove the key from the dictionary
};
Debugger.Break();
}
catch
{
}