I am trying to call the
EnumDisplaySettings/ChangeDisplaySettings Win32 API
functions from C#. I've been following the P/Invoke
tutorial and instructions fairly closely, and although I
can get the code to build and run without a problem, the
calls never return anything useful. I have the equivalent
functionality already running from VB, but I want to get
it working in C#.
I've attached the C# source file containing the P/Invoke
DllImport and struc declarations, as well as the main
method with the relevant calls.
Any help would be greatly appreciated.
Regards,
Louis Castaneda
You have many of the member and parameter datatypes one size too big.
longs should be ints, and ints should be shorts.
Also, I'd recommend that you switch to CharSet.Auto throughout, to get
best performance.
This code works for me.
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct DEVMODE
{
// specify the size of the string arrays to 32
public const int SA_SIZE = 32;
// struct (class) members
[MarshalAs(UnmanagedType.ByValTStr,
SizeConst=SA_SIZE)]
public string lpzDeviceName;
public short iSpecVersion;
public short iDriverVersion;
public short iSize;
public short iDriverExtra;
public int iFields;
public short iOrientation;
public short iPaperSize;
public short iPaperLength;
public short iPaperWidth;
public short iScale;
public short iCopies;
public short iDefaultSource;
public short iPrintQuality;
public short iColor;
public short iDuplex;
public short iYRes;
public short iTTOption;
public short iCollate;
// specify marshalling attrib appropriately for this
type
[MarshalAs(UnmanagedType.ByValTStr,
SizeConst=SA_SIZE)]
public string lpszFormName;
public short iLogPixels;
public int iBitsPerPixel;
public int lPelsWidth;
public int lPelsHeight;
public int lDisplayFlags;
public int lDisplayFreq;
public int lICMMethod;
public int lICMIntent;
public int lMediaType;
public int lDitherType;
public int lReserved1;
public int lReserved2;
public int lPanWidth;
public int lPanHeight;
}
class LibWrapper
{
// do a little P/Invoke stuff here...
// specify the dll containing the desired function and
// the fact that we want to use the default character
set for the call
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern bool
EnumDisplaySettings(string lpszDeviceName,
int lModeNum,
ref DEVMODE lpdm);
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern int
ChangeDisplaySettings([In] ref DEVMODE lpdm,
int iFlags);
}
[STAThread]
static void Main(string[] args)
{
DEVMODE dm = new DEVMODE();
dm.iSize = (short)Marshal.SizeOf(typeof(DEVMODE));
int lMode = -1;
bool b = LibWrapper.EnumDisplaySettings(null, lMode,
ref dm);
}
Mattias
===
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/
Please reply only to the newsgroup.
Thanks very much. That worked perfectly.
Louis
>.
>