2009-04-22 16 views
17

मैंएक्सेल उदाहरण प्राप्त करने के लिए देर से बाध्यकारी उपयोग का उपयोग कैसे करें?

[DllImport("Oleacc.dll")] 
static extern int AccessibleObjectFromWindow(
int hwnd, 
uint dwObjectID, 
byte[] riid, 
ref Excel.Window ptr);

उपयोग कर रहा हूँ उसके हैंडल, जो मैं एक्सेल उदाहरण की प्रक्रिया आईडी से प्राप्त का उपयोग कर एक एक्सेल उदाहरण मिलता है।

यह है कि यह कैसे जब मैं इन समारोह

const uint OBJID_NATIVEOM = 0xFFFFFFF0; 
Guid IID_IDispatch = new Guid("{00020400-0000-0000-C000-000000000046}"); 
Excel.Window ptr = null; 
int hr = AccessibleObjectFromWindow(hwndChild, OBJID_NATIVEOM, 
      IID_IDispatch.ToByteArray(), ref ptr); 

Object objApp = ptr.Application;

कोड का यह शांति अच्छा काम करता है, लेकिन केवल समस्या यह है कि मैं Office 2003 प्राथमिक इंटरॉप विधानसभाओं के लिए एक संदर्भ जोड़ने के लिए किया था है का उपयोग की तरह लग रहा है।

जैसा कि आप देख सकते हैं, फ़ंक्शन में अंतिम पैराम कारण है कि मुझे पियास के संदर्भ को जोड़ने की आवश्यकता क्यों है, इसलिए मेरा सवाल यह है कि यदि इंटरऑप असेंबली के उपयोग से बचने का कोई तरीका है, तो मैंने कोशिश की है देर से बाध्यकारी लेकिन शायद मैं इसे गलत कर रहा हूं क्योंकि मैं इसे काम करने में सक्षम नहीं हूं।

उत्तर

25

पहला: सी # में देर बाध्यकारी काफी दर्द है। इससे बचने के लिए सबसे अच्छा है। दूसरा: सी # में देर बाध्यकारी दर्द है। पीआईए का प्रयोग करें!

ठीक है, कहा जा रहा है कि देर से बाध्यकारी उपयोग करने के लिए आपको क्या करना है: Office 2003 पीआईए के संदर्भ को हटाएं और इसके बजाय AccessibleObjectFromWindow, यानी Excel.Window इंटरफ़ेस द्वारा आवश्यक इंटरफ़ेस का COM आयात जोड़ें:

[Guid("00020893-0000-0000-C000-000000000046")] 
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] 
public interface ExcelWindow 
{ 
} 

आप इस इंटरफेस Reflector की तरह एक उपकरण का उपयोग कर प्राप्त कर सकते हैं (या बस प्रकार Excel.Window पर F12 दबाने जबकि एक्सेल पिया के संदर्भ में अपनी परियोजना में अब भी है) के द्वारा

किया जा रहा है कि आप होगाके हस्ताक्षर को संशोधित करने के लिएआयातित ExcelWindow इंटरफ़ेस मिलान करने के लिए:

[DllImport("Oleacc.dll")] 
static extern int AccessibleObjectFromWindow(int hwnd, uint dwObjectID, byte[] riid, out ExcelWindow ptr); 

अंत में, आप ExcelWindow वस्तु से Excel.Application वस्तु प्राप्त करने के लिए प्रतिबिंब का उपयोग करना चाहिए: अपने कोड में कॉल का एक बहुत बनाने के लिए जा रहा है

object xlApp = ptr.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, ptr, null); 

एक्सेल का ओएम Option Strict बंद (या सी # 4.0 ;-) के लिए प्रतीक्षा करें) के साथ वीबी का उपयोग करना आसान हो सकता है। या, यदि आप सी # से नहीं बदलना चाहते हैं, तो देर से बाइंडिंग कॉल के लिए रैपर क्लास बनाना एक अच्छा विचार हो सकता है।


पूर्ण नमूना

यहाँ

है एक पूरी तरह कार्यात्मक नमूना (एंड्रयू ह्वाइटचैपल द्वारा एक article के आधार पर):

using System; 
using System.Globalization; 
using System.Reflection; 
using System.Runtime.InteropServices; 
using System.Text; 

namespace ExcelLateBindingSample 
{ 
    /// <summary> 
    /// Interface definition for Excel.Window interface 
    /// </summary> 
    [Guid("00020893-0000-0000-C000-000000000046")] 
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] 
    public interface ExcelWindow 
    { 
    } 

    /// <summary> 
    /// This class is needed as a workaround to http://support.microsoft.com/default.aspx?scid=kb;en-us;320369 
    /// Excel automation will fail with the follwoing error on systems with non-English regional settings: 
    /// "Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))" 
    /// </summary> 
    class UILanguageHelper : IDisposable 
    { 
     private CultureInfo _currentCulture; 

     public UILanguageHelper() 
     { 
      // save current culture and set culture to en-US 
      _currentCulture = System.Threading.Thread.CurrentThread.CurrentCulture; 
      System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); 
     } 

     public void Dispose() 
     { 
      // reset to original culture 
      System.Threading.Thread.CurrentThread.CurrentCulture = _currentCulture; 
     } 
    } 

    class Program 
    { 
     [DllImport("user32.dll", SetLastError = true)] 
     static extern IntPtr FindWindow(string lpClassName, string lpWindowName); 

     [DllImport("Oleacc.dll")] 
     static extern int AccessibleObjectFromWindow(int hwnd, uint dwObjectID, byte[] riid, out ExcelWindow ptr); 

     public delegate bool EnumChildCallback(int hwnd, ref int lParam); 

     [DllImport("User32.dll")] 
     public static extern bool EnumChildWindows(int hWndParent, EnumChildCallback lpEnumFunc, ref int lParam); 

     [DllImport("User32.dll")] 
     public static extern int GetClassName(int hWnd, StringBuilder lpClassName, int nMaxCount); 

     public static bool EnumChildProc(int hwndChild, ref int lParam) 
     { 
      StringBuilder buf = new StringBuilder(128); 
      GetClassName(hwndChild, buf, 128); 
      if (buf.ToString() == "EXCEL7") 
      { 
       lParam = hwndChild; 
       return false; 
      } 
      return true; 
     } 

     static void Main(string[] args) 
     { 
      // Use the window class name ("XLMAIN") to retrieve a handle to Excel's main window. 
      // Alternatively you can get the window handle via the process id: 
      // int hwnd = (int)Process.GetProcessById(excelPid).MainWindowHandle; 
      // 
      int hwnd = (int)FindWindow("XLMAIN", null); 

      if (hwnd != 0) 
      { 
       int hwndChild = 0; 

       // Search the accessible child window (it has class name "EXCEL7") 
       EnumChildCallback cb = new EnumChildCallback(EnumChildProc); 
       EnumChildWindows(hwnd, cb, ref hwndChild); 

       if (hwndChild != 0) 
       { 
        // We call AccessibleObjectFromWindow, passing the constant OBJID_NATIVEOM (defined in winuser.h) 
        // and IID_IDispatch - we want an IDispatch pointer into the native object model. 
        // 
        const uint OBJID_NATIVEOM = 0xFFFFFFF0; 
        Guid IID_IDispatch = new Guid("{00020400-0000-0000-C000-000000000046}"); 
        ExcelWindow ptr; 

        int hr = AccessibleObjectFromWindow(hwndChild, OBJID_NATIVEOM, IID_IDispatch.ToByteArray(), out ptr); 

        if (hr >= 0) 
        { 
         // We successfully got a native OM IDispatch pointer, we can QI this for 
         // an Excel Application using reflection (and using UILanguageHelper to 
         // fix http://support.microsoft.com/default.aspx?scid=kb;en-us;320369) 
         // 
         using (UILanguageHelper fix = new UILanguageHelper()) 
         { 
          object xlApp = ptr.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, ptr, null); 

          object version = xlApp.GetType().InvokeMember("Version", BindingFlags.GetField | BindingFlags.InvokeMethod | BindingFlags.GetProperty, null, xlApp, null); 
          Console.WriteLine(string.Format("Excel version is: {0}", version)); 
         } 
        } 
       } 
      } 
     } 
    } 
} 

और VB में पीआईए के बिना यह एक ही समाधान होगा (ध्यान दें कि ओएम कॉल अधिक पढ़ने योग्य है, हालांकि, ओएम तक पहुंच प्राप्त करने के लिए कोड वही होगा):

Option Strict Off 

Imports System.Globalization 
Imports System.Runtime.InteropServices 
Imports System.Text 

Module ExcelLateBindingSample 

    ''' <summary> 
    ''' Interface definition for Excel.Window interface 
    ''' </summary> 
    <Guid("00020893-0000-0000-C000-000000000046"), _ 
    InterfaceType(ComInterfaceType.InterfaceIsIDispatch)> _ 
    Public Interface ExcelWindow 
    End Interface 

    ''' <summary> 
    ''' This class is needed as a workaround to http://support.microsoft.com/default.aspx?scid=kb;en-us;320369 
    ''' Excel automation will fail with the follwoing error on systems with non-English regional settings: 
    ''' "Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))" 
    ''' </summary> 
    Class UILanguageHelper 
     Implements IDisposable 

     Private _currentCulture As CultureInfo 

     Public Sub New() 
      ' save current culture and set culture to en-US 
      _currentCulture = System.Threading.Thread.CurrentThread.CurrentCulture 
      System.Threading.Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US") 
     End Sub 

     Public Sub Dispose() Implements System.IDisposable.Dispose 
      'reset to original culture 
      System.Threading.Thread.CurrentThread.CurrentCulture = _currentCulture 
     End Sub 

    End Class 

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _ 
    Private Function FindWindow(ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr 
    End Function 

    <DllImport("Oleacc.dll")> _ 
    Private Function AccessibleObjectFromWindow(ByVal hwnd As Integer, ByVal dwObjectID As UInt32, ByVal riid() As Byte, ByRef ptr As ExcelWindow) As Integer 
    End Function 

    Public Delegate Function EnumChildCallback(ByVal hwnd As Integer, ByRef lParam As Integer) As Boolean 

    <DllImport("User32.dll")> _ 
    Public Function EnumChildWindows(ByVal hWndParent As Integer, ByVal lpEnumFunc As EnumChildCallback, ByRef lParam As Integer) As Boolean 
    End Function 

    <DllImport("User32.dll")> _ 
    Public Function GetClassName(ByVal hWnd As Integer, ByVal lpClassName As StringBuilder, ByVal nMaxCount As Integer) As Integer 
    End Function 

    Public Function EnumChildProc(ByVal hwndChild As Integer, ByRef lParam As Integer) As Boolean 
     Dim buf As New StringBuilder(128) 
     GetClassName(hwndChild, buf, 128) 
     If buf.ToString() = "EXCEL7" Then 
      lParam = hwndChild 
      Return False 
     End If 
     Return True 
    End Function 

    Sub Main() 
     ' Use the window class name ("XLMAIN") to retrieve a handle to Excel's main window. 
     ' Alternatively you can get the window handle via the process id: 
     ' Dim hwnd As Integer = CInt(Process.GetProcessById(excelPid).MainWindowHandle); 
     ' 
     Dim hwnd As Integer = CInt(FindWindow("XLMAIN", Nothing)) 

     If hwnd <> 0 Then 
      Dim hwndChild As Integer = 0 

      ' Search the accessible child window (it has class name "EXCEL7") 
      Dim cb As New EnumChildCallback(AddressOf EnumChildProc) 
      EnumChildWindows(hwnd, cb, hwndChild) 

      If hwndChild <> 0 Then 
       ' We call AccessibleObjectFromWindow, passing the constant OBJID_NATIVEOM (defined in winuser.h) 
       ' and IID_IDispatch - we want an IDispatch pointer into the native object model. 
       ' 
       Const OBJID_NATIVEOM As UInteger = &HFFFFFFF0& 
       Dim IID_IDispatch As New Guid("{00020400-0000-0000-C000-000000000046}") 
       Dim ptr As ExcelWindow 

       Dim hr As Integer = AccessibleObjectFromWindow(hwndChild, OBJID_NATIVEOM, IID_IDispatch.ToByteArray(), ptr) 

       If hr >= 0 Then 
        ' We successfully got a native OM IDispatch pointer, we can QI this for 
        ' an Excel Application using reflection (and using UILanguageHelper to 
        ' fix http://support.microsoft.com/default.aspx?scid=kb;en-us;320369) 
        ' 
        Using fixCrash As New UILanguageHelper 
         Console.WriteLine(String.Format("Excel version is: {0}", ptr.Application.Version)) 
        End Using 
       End If 
      End If 
     End If 

    End Sub 

End Module 
+5

इससे मेरा सिर चोट लग रहा है। –

+7

+1 वास्तव में प्रभावशाली काम, divo। और वीबी के साथ ही सी # में दिखाया गया है? मुझे खेद है कि हम केवल एक बार मतदान करने तक ही सीमित हैं। –

+2

बहुत धन्यवाद, क्योंकि माइक का कहना है कि यह एक प्रभावशाली काम है, यह वही है जो मुझे चाहिए था। – Vic

0

मत करो।

मुझे पता है कि यह पतला लगता है, लेकिन एक्सेल के साथ काम करते समय वीबी कई बार कई बार उपयोग करना आसान है। यहां तक ​​कि यदि आप देर से बाध्यकारी के बजाय पीआईए का उपयोग करते हैं, तो भी आप वीबी का उपयोग करने से बेहतर हैं।

(नोट:। जब सी # 4 जारी किया गया है इन सभी टिप्पणियों तुरन्त गलत हो जाएगा)

5

बजाय AccessibleObjectFromWindow की इस परिभाषा का उपयोग करें:

[DllImport("Oleacc.dll")] 
    private static extern int AccessibleObjectFromWindow(
     int hwnd, uint dwObjectID, 
     byte[] riid, 
     [MarshalAs(UnmanagedType.IUnknown)]ref object ptr); 
+2

+1, पीआईए का उपयोग किये बिना या एक डमी इंटरफ़ेस को परिभाषित किए बिना 'एक्सेस। एप्लिकेशन' उदाहरण प्राप्त करने के लिए बहुत अच्छा काम करता है। – Heinzi

3

पहले उत्तर में कोड एक आकर्षण की तरह काम किया। वर्ड के लिए वही बात है, साथ ही नीचे .NET 4.0 गतिशील कार्रवाई का थोड़ा सा है।

// http://stackoverflow.com/questions/779363/how-to-use-use-late-binding-to-get-excel-instance 
// ReSharper disable InconsistentNaming 

using System; 
using System.Runtime.InteropServices; 
using System.Globalization; 
using System.Reflection; 
using System.Text; 

namespace LateBindingWord { 
    /// <summary> Interface definition for Word.Window interface </summary> 
    [Guid("00020962-0000-0000-C000-000000000046")] 
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] 
    public interface IWordWindow { 
    } 

    /// <summary> 
    /// This class is needed as a workaround to http://support.microsoft.com/default.aspx?scid=kb;en-us;320369 
    /// Excel automation will fail with the follwoing error on systems with non-English regional settings: 
    /// "Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))" 
    /// </summary> 
    class UiLanguageHelper : IDisposable { 
     private readonly CultureInfo _currentCulture; 

     public UiLanguageHelper() { 
      // save current culture and set culture to en-US 
      _currentCulture = System.Threading.Thread.CurrentThread.CurrentCulture; 
      System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); 
     } 

     public void Dispose() { 
      // reset to original culture 
      System.Threading.Thread.CurrentThread.CurrentCulture = _currentCulture; 
     } 
    } 

    class Program { 
     [DllImport("user32.dll", SetLastError = true)] 
     static extern IntPtr FindWindow(string lpClassName, string lpWindowName); 

     [DllImport("Oleacc.dll")] 
     static extern int AccessibleObjectFromWindow(int hwnd, uint dwObjectID, byte[] riid, out IWordWindow ptr); 

     public delegate bool EnumChildCallback(int hwnd, ref int lParam); 

     [DllImport("User32.dll")] 
     public static extern bool EnumChildWindows(int hWndParent, EnumChildCallback lpEnumFunc, ref int lParam); 

     [DllImport("User32.dll")] 
     public static extern int GetClassName(int hWnd, StringBuilder lpClassName, int nMaxCount); 

     public static bool EnumChildProc(int hwndChild, ref int lParam) { 
      var buf = new StringBuilder(128); 
      GetClassName(hwndChild, buf, 128); 
      Console.WriteLine(buf.ToString()); 

      if (buf.ToString() == "_WwG") { 
       lParam = hwndChild; 
       return false; 
      } 
      return true; 
     } 

     static void Main() { 
      // Use the window class name ("XLMAIN") to retrieve a handle to Excel's main window. 
      // Alternatively you can get the window handle via the process id: 
      // int hwnd = (int)Process.GetProcessById(excelPid).MainWindowHandle; 
      // var p=Process.GetProcesses().FirstOrDefault(x => x.ProcessName=="WINWORD"); 
      var hwnd = (int) FindWindow("OpusApp", null); 

      if (hwnd == 0) 
       throw new Exception("Can't find Word"); 

      // Search the accessible child window (it has class name "_WwG") // http://msdn.microsoft.com/en-us/library/windows/desktop/dd317978%28v=vs.85%29.aspx 
      var hwndChild = 0; 
      var cb = new EnumChildCallback(EnumChildProc); 
      EnumChildWindows(hwnd, cb, ref hwndChild); 

      if (hwndChild == 0) 
       throw new Exception("Can't find Automation Child Window"); 

      // We call AccessibleObjectFromWindow, passing the constant OBJID_NATIVEOM (defined in winuser.h) 
      // and IID_IDispatch - we want an IDispatch pointer into the native object model. 
      const uint OBJID_NATIVEOM = 0xFFFFFFF0; 
      var IID_IDispatch = new Guid("{00020400-0000-0000-C000-000000000046}"); 
      IWordWindow ptr; 

      var hr = AccessibleObjectFromWindow(hwndChild, OBJID_NATIVEOM, IID_IDispatch.ToByteArray(), out ptr); 

      if (hr < 0) 
       throw new Exception("Can't get Accessible Object"); 

      // We successfully got a native OM IDispatch pointer, we can QI this for 
      // an Excel Application using reflection (and using UILanguageHelper to 
      // fix http://support.microsoft.com/default.aspx?scid=kb;en-us;320369) 
      using (new UiLanguageHelper()) { 
       var wordApp = ptr.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, ptr, null); 

       var version = wordApp.GetType().InvokeMember("Version", BindingFlags.GetField | BindingFlags.InvokeMethod | BindingFlags.GetProperty, null, wordApp, null); 
       Console.WriteLine("Word version is: {0}", version); 

       dynamic wordAppd = ptr.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, ptr, null); 
       Console.WriteLine("Version: " + wordAppd.Version); 
      } 
     } 
    } 
} 
+0

मुझे पता है कि यह शांत है, लेकिन मुझे ** घंटा = -214746725 9 ** मिल रहा है, क्या आपको पता है कि ऐसा क्यों हो सकता है? –

संबंधित मुद्दे

 संबंधित मुद्दे