简体   繁体   中英

Code Analysis CA1060 Fix

I have the following code in my application:

[DllImport("user32.dll")]
private static extern int GetWindowLong(IntPtr hwnd, int index);

[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle);

[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter,
               int x, int y, int width, int height, uint flags);

[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hwnd, uint msg,
               IntPtr wParam, IntPtr lParam);

I am getting the following warning from Code Analysis (FxCop):

CA1060 : Microsoft.Design : Because it is a P/Invoke method, 'IconHelper.GetWindowLong(IntPtr, int)' should be defined in a class named NativeMethods, SafeNativeMethods, or UnsafeNativeMethods.

Can someone tell me which class I should put them in? I don't know if it is Native, SafeNative, or UnsafeNative.

You have detailed information about this warning here: http://msdn.microsoft.com/en-us/library/ms182161.aspx . In short:

For most applications, moving P/Invokes to a new class that is named NativeMethods is enough.

Try moving them all into a NativeMethod class, it will solve the problem

Your code should look like this after fixing it

public class NativeMethods {
[DllImport("user32.dll")]
private static extern int GetWindowLong(IntPtr hwnd, int index);

[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle);

[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter,
               int x, int y, int width, int height, uint flags);

[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hwnd, uint msg,
               IntPtr wParam, IntPtr lParam);
}

Remember to change all the places where you are calling these methods

Before change

SendMessage(IntPtr hwnd, uint msg,IntPtr wParam, IntPtr lParam)

should be

NativeMethods.SendMessage(IntPtr hwnd, uint msg,IntPtr wParam, IntPtr lParam)

You can suppress this warning by defining

<PropertyGroup> 
..... 
     <NoWarn>CA1060</NoWarn>
..... 
</PropertyGroup>

in the configuration file (.csproj file).

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