11

I tried:

  • To add user32.dll from Reference Manager, and imported it from Windows\System32\user32.dll, I got Error Message:

    A reference to 'C:\Windows\System32\user32.dll couldn't be added. Please make sure that the file is accessible, and that it is a valid assembly or COM component.

  • using System.Runtime.InteropServices; [DllImport("user32")]

  • To launch Visual Studio as Administrator

Nothing works... it goes on my nerves I am trying 2 hours to import this damn .dll...

Yoav Feuerstein
  • 1,925
  • 2
  • 22
  • 53
jovanMeshkov
  • 757
  • 5
  • 12
  • 29

2 Answers2

11

You do not need to add a reference to User32.dll. It is part of Windows and can be imported in your code without adding a reference. You do this using P/Invoke.

[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void SetWindowText(int hWnd, String text);

private void button3_Click(object sender, EventArgs e)
{
    IntPtr wHnd = this.Handle;//assuming you are in a C# form application
    SetWindowText(wHnd.ToInt32(), "New Window Title");
}

See Also:

jrbeverly
  • 1,611
  • 14
  • 20
  • Thank you! I didn't realize/know that method should be defined ( public static extern void SetWindowText(int hWnd, String text); ) – jovanMeshkov Jul 28 '13 at 20:23
  • Well it is not that method purely that needs to be defined. Each method that you reference from `user32.dll` must be present in that format: `[System.Runtime.InteropServices.DllImport("user32.dll")]` `public static extern void ();` – jrbeverly Jul 28 '13 at 21:15
1

It's not a .NET dll. You don't "add reference" the same way you do with .NET dlls. Instead you have to add P/Invoke code to your app to invoke the functions you want. Here's a good resource for learning pinvoke: http://pinvoke.net/

Dax Fohl
  • 10,654
  • 6
  • 46
  • 90