今天注册了blog,先来一篇简单实用的文章吧~
以前大家可能碰到过这样的需求,
要求程序检查.xls文件有没有被Excel打开着,我想很多朋友都会想到利用系统api.获得进程窗体的句柄等...
前面一段时间,正好碰到了这样需求,所以调查了一下,其实oledb公开了一些api,可供我们使用.
如代码
[DllImport("ole32.dll")]
public static extern int GetRunningObjectTable(int reserved, out IRunningObjectTable prot);
[DllImport("ole32.dll")]
public static extern int CreateBindCtx(int reserved, out IBindCtx ppbc);
public static extern int GetRunningObjectTable(int reserved, out IRunningObjectTable prot);
[DllImport("ole32.dll")]
public static extern int CreateBindCtx(int reserved, out IBindCtx ppbc);
private Hashtable GetRunningObjectTable()
{
Hashtable result = new Hashtable();
IntPtr numFetched = IntPtr.Zero;
IRunningObjectTable runningObjectTable;
IEnumMoniker monikerEnumerator;
IMoniker[] monikers = new IMoniker[1];
GetRunningObjectTable(0, out runningObjectTable);
runningObjectTable.EnumRunning(out monikerEnumerator);
monikerEnumerator.Reset();
while (monikerEnumerator.Next(1, monikers, numFetched) == 0)
{
IBindCtx ctx;
CreateBindCtx(0, out ctx);
string runningObjectName;
monikers[0].GetDisplayName(ctx, null, out runningObjectName);
object runningObjectVal;
runningObjectTable.GetObject(monikers[0], out
runningObjectVal);
result[runningObjectName] = runningObjectVal;
}
return result;
}
private bool XlsIsOpen(string fileName)
{
bool XlsIsOpen = false;
Hashtable rot = GetRunningObjectTable();
bool isOk = false;
foreach (object o in rot.Values)
{
if (isOk)
{
break;
}
Excel.Application a = o as Excel.Application;
if (a != null)
{
Excel.Workbooks wbooks = a.Workbooks;
foreach (Excel.Workbook wb in wbooks)
{
if (wb.Name == fileName)
{
XlsIsOpen = true;
isOk = true;
break;
}
}
//a.DisplayAlerts = false;
//a.Quit();
}
}
return XlsIsOpen;
}
{
Hashtable result = new Hashtable();
IntPtr numFetched = IntPtr.Zero;
IRunningObjectTable runningObjectTable;
IEnumMoniker monikerEnumerator;
IMoniker[] monikers = new IMoniker[1];
GetRunningObjectTable(0, out runningObjectTable);
runningObjectTable.EnumRunning(out monikerEnumerator);
monikerEnumerator.Reset();
while (monikerEnumerator.Next(1, monikers, numFetched) == 0)
{
IBindCtx ctx;
CreateBindCtx(0, out ctx);
string runningObjectName;
monikers[0].GetDisplayName(ctx, null, out runningObjectName);
object runningObjectVal;
runningObjectTable.GetObject(monikers[0], out
runningObjectVal);
result[runningObjectName] = runningObjectVal;
}
return result;
}
private bool XlsIsOpen(string fileName)
{
bool XlsIsOpen = false;
Hashtable rot = GetRunningObjectTable();
bool isOk = false;
foreach (object o in rot.Values)
{
if (isOk)
{
break;
}
Excel.Application a = o as Excel.Application;
if (a != null)
{
Excel.Workbooks wbooks = a.Workbooks;
foreach (Excel.Workbook wb in wbooks)
{
if (wb.Name == fileName)
{
XlsIsOpen = true;
isOk = true;
break;
}
}
//a.DisplayAlerts = false;
//a.Quit();
}
}
return XlsIsOpen;
}