您的位置:首页 > 其它

Lync二次开发关于Lync启动退出问题

2013-07-02 10:40 204 查看
以前使用C++开发的version.dll文件,由于各个用户环境的不同,造成某些用户加载不了我们开发的插件,并且写version.dll的同事还没找到好的解决办法,所以得换一种思路去解决这个问题,就是Lync启动时加载我们的插件。

因此写了一个winform程序来监控进程的变化,这个程序还要设置为开机启动。下面是主要代码:

public partial class IcoLyncForm : Form
{
[DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)]
static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

public IcoLyncForm()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
}

void Form1_Load(object sender, EventArgs e)
{
Process[] p = Process.GetProcessesByName("lync");
if (p.Length > 0)
{
lyncnet.clsLyncNet cls = new lyncnet.clsLyncNet();
this.Invoke(new Action(() => { cls.NetMain(); }));
}

//创建WQL事件查询,用于实例创建
var qCreate = new WqlEventQuery("__InstanceCreationEvent",
TimeSpan.FromSeconds(1),  //WHTHIN = 1
"TargetInstance ISA 'Win32_Process'");
//创建WQL事件查询,用于实例删除
var qDelete = new WqlEventQuery("__InstanceDeletionEvent",
TimeSpan.FromSeconds(1),  //WHTHIN = 1
"TargetInstance ISA 'Win32_Process'");

//创建事件查询的侦听器(ManagementEventWatcher)
var wCreate = new ManagementEventWatcher(qCreate);
var wDelete = new ManagementEventWatcher(qDelete);

wCreate.EventArrived += new EventArrivedEventHandler(wCreate_EventArrived);
wDelete.EventArrived += new EventArrivedEventHandler(wDelete_EventArrived);

//异步开始侦听
wCreate.Start();
wDelete.Start();

IntPtr intptr;
try
{
do
{
intptr = FindWindow(null, "ICOLync");
if (intptr != IntPtr.Zero)
{
ShowWindow(intptr, 0);
}
}
while (intptr == IntPtr.Zero);
IcoLync.Util.RegistryHelper.RunWhenStart(true, "ICOLync", AppDomain.CurrentDomain.BaseDirectory + "ICOLync.exe");
}
catch (Exception ex)
{
Logger.Error(ex);
}
}

//输出事件对应的ManagementBaseObject(本例中的Win32_Process实例)的信息
static string GetInfo(ManagementBaseObject mobj)
{
var instance = (ManagementBaseObject)mobj["TargetInstance"];
return instance["Name"].ToString();
}

void wCreate_EventArrived(object sender, EventArrivedEventArgs e)
{
if (GetInfo(e.NewEvent).Equals("lync.exe"))
{
lyncnet.clsLyncNet cls = new lyncnet.clsLyncNet();
this.Invoke(new Action(() => { cls.NetMain(); }));
}
}

void wDelete_EventArrived(object sender, EventArrivedEventArgs e)
{
if (GetInfo(e.NewEvent).Equals("lync.exe")) this.RestartMe();
}

private void RestartMe()
{
Program._run.Close();
Process.Start(Application.ExecutablePath);
Process.GetCurrentProcess().Kill();
}
}


View Code
这个winform程序启动之后调用win32 api隐藏起来。检测到新增Lync.exe进程时,注册ICOLync插件,Lync.exe进程注销后,重启winform程序。开始还考虑把winform程序的进程保护起来,很麻烦,不同的操作系统,出现的状况还不一样,所以取消了。

2013.7.26修改:

使用System.Threading.Mutex互斥体,实现程序只启动单一进程,发现有一个Bug,在windows多用户的情况下,每一个用户都可以启动一个进程,所以要保持整天计算机只启动一个进程,应改为如下:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐