PreviewHandler用法(三)

来源:互联网 发布:计算机c语言自学教程 编辑:程序博客网 时间:2024/06/06 00:55

    四.C#如何与COM进行交互

    由于IPreviewHandlerCOM接口,要想在C#中用,那么就要把它导入到C#中来,用[ComImport]标记可以将COM接口导入到C#中。ComImport的含义是指示该属性化类型是以前在COM 中定义的。在接口导入后,要对接口里的函数进行定义,不然C#中的程序就用不了。代码如下:

[ComImport][InterfaceType(ComInterfaceType.InterfaceIsIUnknown)][Guid("8895b1c6-b41f-4c1c-a562-0d564250836f")]interface IPreviewHandler{    void SetWindow(IntPtr hwnd, ref RECT rect);    void SetRect(ref RECT rect);    void DoPreview();    void Unload();    void SetFocus();    void QueryFocus(out IntPtr phwnd);    [PreserveSig]    uint TranslateAccelerator(ref MSG pmsg);} [ComImport][InterfaceType(ComInterfaceType.InterfaceIsIUnknown)][Guid("b7d14566-0509-4cce-a71f-0a554233bd9b")]interface IInitializeWithFile{    void Initialize([MarshalAs(UnmanagedType.LPWStr)] string pszFilePath, uint grfMode);} [ComImport][InterfaceType(ComInterfaceType.InterfaceIsIUnknown)][Guid("b824b49d-22ac-4161-ac8a-9916e8fa3f7f")]interface IInitializeWithStream{    void Initialize(IStream pstream, uint grfMode);}[StructLayout(LayoutKind.Sequential)]public struct RECT{    public int left;public int top;    public int right;    public int bottom;    public RECT(Rect rect)    {        this.top = (int)rect.Top;        this.bottom = (int)rect.Bottom;        this.left = (int)rect.Left;        this.right = (int)rect.Right;    }} 

    关于COM接口函数参数类型在C#中对应类型是什么的问题,据我所知,没有那么一个对应表,我觉得这就看你的经验了,其实做多了,也就知道。比如说:

       HANDLE –> IntPtr

       IN LPCTSTR pszBuffer –> String

       OUT LPTSTR pszBuffer –> ref StringBuilder,而不是String, C++中遇到这种类型的参数,一般是传一个数组BUFFER的地址,让函数给这个BUFFER填充值,所以在这里对应的C#类型就应该为StringBuilder,而不是String,因为尽管String是引用类型,但做参数时是当值类型的。


原创粉丝点击