简体   繁体   中英

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

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..

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);

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM