开发者

How to add reference to a COM component in my project in C#.NET in Visual Studio 2005?

开发者 https://www.devze.com 2023-01-23 09:43 出处:网络
How can I add a reference of a COM DLL in my application? I have tried to add kernel32.dll and user32.dll but these are not supporting开发者_运维问答..You should not need to add a reference to either

How can I add a reference of a COM DLL in my application?

I have tried to add kernel32.dll and user32.dll but these are not supporting开发者_运维问答..


You should not need to add a reference to either kernel32.dll or user32.dll. These DLLs are part of Windows and can be imported in your code without adding a reference. You do this using P/Invoke.

For example, to call the function SendMessage in user32.dll, you could use the following C# code:

[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

For more information and code snippets for methods in these DLLs, check out the P/Invoke wiki.

EDIT: You may also check out this article from the MSDN magazine for more information about P/Invoking and specifically some of the author's comments about style and best practices.


user32.dll etc are not COM dlls. You will need to use P/Invoke via [DllImport], for example (from msdn):

// Use DllImport to import the Win32 MessageBox function.
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int MessageBox(IntPtr hWnd, String text,
     String caption, uint type);


To reference a COM componennt in Visual Studio 2005:

  1. Choose Add Reference from the Project menu1.
  2. Choose the COM tab2.
  3. Select the componet you want to reference and click OK.

It may be that what you actually want to do is call an unmanaged function residing within a DLL. For this you need to use P/Invoke.

Marc Gravell's answer covers the syntax for this, but you can get more information by looking at the documentation for Platform Invoke on MSDN and to quickly find the correct signature for a specific function check out PInvoke.net

0

精彩评论

暂无评论...
验证码 换一张
取 消