【发布时间】:2016-09-16 18:07:39
【问题描述】:
我正在做一个应用程序,当我启动 MS Word 应用程序时,
会创建一个按钮,而当 MS Word 应用程序关闭时,该按钮会被删除。
所以这就是我将 MS Word 和按钮关联起来的方法......
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;
}
但我在这里遇到错误mapping.Add(new KeyValuePair<int, Button>(processId, deleteButton));
我收到此错误:“Add 没有重载方法需要 1 个参数”...
我该怎么办?
有没有其他解决方案?
谢谢。
编辑:
我已经修改了我的代码,但我只能删除我创建的最后一个按钮,当我想删除其他我不能删除的按钮时...我设置了断点以了解不同变量的值。
但是当我创建 2 个按钮时,mapping.add 中的计数始终等于 1... 正常吗?
这里是代码:
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
{
}
【问题讨论】:
-
我不知道如何回答你的实际问题,但你得到的错误是不言自明的。 Dictionary
.Add 没有重载,只需要 1 个参数!与其将 KeyValuePair 作为一个参数传递,不如将键和值按该顺序作为两个单独的参数传递。 -
您可以参考here解决方案。