There are already many answers about this topic, but is there a single way to get the the total amount of memory on a windows system from XP and above including Windows Server 2003?
What I have found:
Win32_LogicalMemoryConfiguration (Deprecated)
Win32_ComputerSystem (Minimum supported client: Vista)
Microsoft.VisualBasic.Devices.ComputerInfo (no XP support according to platforms)
thx
Add reference to Microsoft.VisualBasic and
var info = new Microsoft.VisualBasic.Devices.ComputerInfo();
Debug.WriteLine(info.TotalPhysicalMemory);
Debug.WriteLine(info.AvailablePhysicalMemory);
Debug.WriteLine(info.TotalVirtualMemory);
Debug.WriteLine(info.AvailableVirtualMemory);
edit : How can I get the total physical memory in C#?
or
You can make use of GlobalMemoryStatusEx : Example Here
private void DisplayMemory()
{
// Consumer of the NativeMethods class shown below
long tm = System.GC.GetTotalMemory(true);
NativeMethods oMemoryInfo = new NativeMethods();
this.lblMemoryLoadNumber.Text = oMemoryInfo.MemoryLoad.ToString();
this.lblIsMemoryTight.Text = oMemoryInfo.isMemoryTight().ToString();
if (oMemoryInfo.isMemoryTight())
this.lblIsMemoryTight.Text.Font.Bold = true;
else
this.lblIsMemoryTight.Text.Font.Bold = false;
}
Native class wrapper.
[CLSCompliant(false)]
public class NativeMethods {
private MEMORYSTATUSEX msex;
private uint _MemoryLoad;
const int MEMORY_TIGHT_CONST = 80;
public bool isMemoryTight()
{
if (_MemoryLoad > MEMORY_TIGHT_CONST )
return true;
else
return false;
}
public uint MemoryLoad
{
get { return _MemoryLoad; }
internal set { _MemoryLoad = value; }
}
public NativeMethods() {
msex = new MEMORYSTATUSEX();
if (GlobalMemoryStatusEx(msex)) {
_MemoryLoad = msex.dwMemoryLoad;
//etc.. Repeat for other structure members
}
else
// Use a more appropriate Exception Type. 'Exception' should almost never be thrown
throw new Exception("Unable to initalize the GlobalMemoryStatusEx API");
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
private class MEMORYSTATUSEX
{
public uint dwLength;
public uint dwMemoryLoad;
public ulong ullTotalPhys;
public ulong ullAvailPhys;
public ulong ullTotalPageFile;
public ulong ullAvailPageFile;
public ulong ullTotalVirtual;
public ulong ullAvailVirtual;
public ulong ullAvailExtendedVirtual;
public MEMORYSTATUSEX()
{
this.dwLength = (uint) Marshal.SizeOf(typeof( MEMORYSTATUSEX ));
}
}
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool GlobalMemoryStatusEx( [In, Out] MEMORYSTATUSEX lpBuffer);
}
Related
How do I subscribe to Windows Low memory notification from c# ?
our c# app has substantial unmanaged memory allocation, which we can free if OS memory availability is low.
Using CreateMemoryResourceNotification and QueryMemoryResourceNotification to check memory status
enum MemoryResourceNotificationType : int
{
LowMemoryResourceNotification = 0,
HighMemoryResourceNotification = 1,
}
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr CreateMemoryResourceNotification(MemoryResourceNotificationType notificationType);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool QueryMemoryResourceNotification(IntPtr resourceNotificationHandle, out int resourceState);
private static IntPtr MemoryResourceNotificationHandle;
public static void TryReclaim()
{
MemoryResourceNotificationHandle = CreateMemoryResourceNotification(MemoryResourceNotificationType.LowMemoryResourceNotification);
int sleepIntervalInMs = ReclaimIntervalInSeconds * 1000;
while (true)
{
Thread.Sleep(10_000);
bool isSuccecced = QueryMemoryResourceNotification(MemoryResourceNotificationHandle, out int memoryStatus);
if (isSuccecced)
{
if (memoryStatus >= 1)
{
DoReclaim();
}
}
}
}
I would like to enable or disable phone radio in low connectivity areas. Is it possible to do this? I am using motorola ES400 for development.
First : Import these dlls
[DllImport("ossvcs.dll", EntryPoint = "#276", CharSet = CharSet.Unicode)]
private static extern uint GetWirelessDevice(ref IntPtr pDevice, int pDevVal);
[DllImport("ossvcs.dll", EntryPoint = "#273", CharSet = CharSet.Unicode)]
private static extern uint ChangeRadioState(ref RDD pDevice, int dwState, int saveAction);
[DllImport("ossvcs.dll", EntryPoint = "#280", CharSet = CharSet.Unicode)]
private static extern uint FreeDeviceList(IntPtr pDevice);
And here's a copy of the code I use for the Motorola MC65, which should work for yours as well.
[StructLayout(LayoutKind.Auto)]
struct RADIODEVSTATE
{
public const int RADIODEVICES_ON = 1;
public const int RADIODEVICES_OFF = 0;
}
/*
typedef enum _RADIODEVTYPE
{
RADIODEVICES_MANAGED = 1,
RADIODEVICES_PHONE,
RADIODEVICES_BLUETOOTH,
} RADIODEVTYPE;
*/
[StructLayout(LayoutKind.Auto, CharSet = CharSet.Unicode)]
struct RADIODEVTYPE
{
public const int RADIODEVICES_MANAGED = 1;
public const int RADIODEVICES_PHONE = 2;
public const int RADIODEVICES_BLUETOOTH = 3;
}
/*
typedef enum _SAVEACTION
{
RADIODEVICES_DONT_SAVE = 0,
RADIODEVICES_PRE_SAVE,
RADIODEVICES_POST_SAVE,
} SAVEACTION;
*/
[StructLayout(LayoutKind.Auto, CharSet = CharSet.Unicode)]
struct SAVEACTION
{
public const int RADIODEVICES_DONT_SAVE = 0;
public const int RADIODEVICES_PRE_SAVE = 1;
public const int RADIODEVICES_POST_SAVE = 2;
}
/*
struct RDD
{
RDD() : pszDeviceName(NULL), pNext(NULL), pszDisplayName(NULL) {}
~RDD() { LocalFree(pszDeviceName); LocalFree(pszDisplayName); }
LPTSTR pszDeviceName; // Device name for registry setting.
LPTSTR pszDisplayName; // Name to show the world
DWORD dwState; // ON/off/[Discoverable for BT]
DWORD dwDesired; // desired state - used for setting registry etc.
RADIODEVTYPE DeviceType; // Managed, phone, BT etc.
RDD * pNext; // Next device in list
}; //radio device details
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct RDD
{
[MarshalAs(UnmanagedType.LPTStr)]
public string pszDeviceName;
[MarshalAs(UnmanagedType.LPTStr)]
public string pszDisplayName;
public uint dwState;
public uint dwDesired;
public int DeviceType;
public IntPtr pNext;
}
private static bool SetDeviceState(int dwDevice, int dwState)
{
var pDevice = new IntPtr(0);
//Get the first wireless device
var result = GetWirelessDevice(ref pDevice, 0);
if (result != 0)
return false;
//While we're still looking at wireless devices
while (pDevice != IntPtr.Zero)
{
//Marshall the pointer into a C# structure
var device = (RDD)System.Runtime.InteropServices.Marshal.PtrToStructure(pDevice, typeof(RDD));
//If this device is the device we're looking for
if (device.DeviceType == dwDevice)
{
//Change the state of the radio
result = ChangeRadioState(ref device, dwState, SAVEACTION.RADIODEVICES_PRE_SAVE);
}
//Set the pointer to the next device in the linked list
pDevice = device.pNext;
}
//Free the list of devices
FreeDeviceList(pDevice);
//Turning off radios doesn't correctly report the status, so return true anyway.
return result == 0 || dwState == RADIODEVSTATE.RADIODEVICES_OFF;
}
And to turn off the phone simply call following method:
/// <summary>
/// Disables the phone radio on device
/// </summary>
public void DisablePhoneRadio()
{
SetDeviceState(RADIODEVTYPE.RADIODEVICES_PHONE, RADIODEVSTATE.RADIODEVICES_OFF);
}
So just use whatever conditional statements are needed and call DisablePhoneRadio() whenever you need to disable it, and when enabling the phone radio simply swat out the RADIODEVSTATE.RADIODEVICES_OFF with RADIODEVSTATE.RADIODEVICES_ON like so:
/// <summary>
/// Enables the phone radio on device
/// </summary>
public void EnablePhoneRadio()
{
SetDeviceState(RADIODEVTYPE.RADIODEVICES_PHONE, RADIODEVSTATE.RADIODEVICES_ON);
}
Hope this helps!
You need to P/Invoke GetDeviceList and ChangeRadioState from ossvcs.dll. The code to actually do this is a bit long for a SO post, so I'll leave it to you to get it worked out - it's not terribly hard (there's some C code here, and there's some C# code on CodeProject even, I've not used it so YMMV).
Another alternative is to use the Radios class in the SDF, which already has these wrapped.
Check this thread as well. Interesting take on threaded calls and monitoring the device connectivity state and powering on and off the cellular radio on windows mobile.
http://www.codeproject.com/Messages/4117749/Re-Csharp-Wrapper.aspx
I have seen posts on changing console true type font and console colors (rgb) but nothing on setting or getting the console font size.
The reason I want to change the font size is because a grid is printed to the console, and the grid has many columns, so, it fits better with a smaller font. I'm wondering if it's possible to change it at runtime rather than allowing the default or configured fonts to take priority / override inheritance.
Maybe this article can help you
ConsoleHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;
namespace ConsoleExtender {
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct ConsoleFont {
public uint Index;
public short SizeX, SizeY;
}
public static class ConsoleHelper {
[DllImport("kernel32")]
public static extern bool SetConsoleIcon(IntPtr hIcon);
public static bool SetConsoleIcon(Icon icon) {
return SetConsoleIcon(icon.Handle);
}
[DllImport("kernel32")]
private extern static bool SetConsoleFont(IntPtr hOutput, uint index);
private enum StdHandle {
OutputHandle = -11
}
[DllImport("kernel32")]
private static extern IntPtr GetStdHandle(StdHandle index);
public static bool SetConsoleFont(uint index) {
return SetConsoleFont(GetStdHandle(StdHandle.OutputHandle), index);
}
[DllImport("kernel32")]
private static extern bool GetConsoleFontInfo(IntPtr hOutput, [MarshalAs(UnmanagedType.Bool)]bool bMaximize,
uint count, [MarshalAs(UnmanagedType.LPArray), Out] ConsoleFont[] fonts);
[DllImport("kernel32")]
private static extern uint GetNumberOfConsoleFonts();
public static uint ConsoleFontsCount {
get {
return GetNumberOfConsoleFonts();
}
}
public static ConsoleFont[] ConsoleFonts {
get {
ConsoleFont[] fonts = new ConsoleFont[GetNumberOfConsoleFonts()];
if(fonts.Length > 0)
GetConsoleFontInfo(GetStdHandle(StdHandle.OutputHandle), false, (uint)fonts.Length, fonts);
return fonts;
}
}
}
}
Here is how to use it to list true type fonts for console,
static void Main(string[] args) {
var fonts = ConsoleHelper.ConsoleFonts;
for(int f = 0; f < fonts.Length; f++)
Console.WriteLine("{0}: X={1}, Y={2}",
fonts[f].Index, fonts[f].SizeX, fonts[f].SizeY);
ConsoleHelper.SetConsoleFont(5);
ConsoleHelper.SetConsoleIcon(SystemIcons.Information);
}
Crucial functions: SetConsoleFont, GetConsoleFontInfo and GetNumberOfConsoleFonts. They're undocumented, so use at your own risk.
In this thread I found a much more elegant solution that now works perfectly fine.
ConsoleHelper.cs:
using System;
using System.Runtime.InteropServices;
public static class ConsoleHelper
{
private const int FixedWidthTrueType = 54;
private const int StandardOutputHandle = -11;
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern IntPtr GetStdHandle(int nStdHandle);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool SetCurrentConsoleFontEx(IntPtr hConsoleOutput, bool MaximumWindow, ref FontInfo ConsoleCurrentFontEx);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool GetCurrentConsoleFontEx(IntPtr hConsoleOutput, bool MaximumWindow, ref FontInfo ConsoleCurrentFontEx);
private static readonly IntPtr ConsoleOutputHandle = GetStdHandle(StandardOutputHandle);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct FontInfo
{
internal int cbSize;
internal int FontIndex;
internal short FontWidth;
public short FontSize;
public int FontFamily;
public int FontWeight;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
//[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.wc, SizeConst = 32)]
public string FontName;
}
public static FontInfo[] SetCurrentFont(string font, short fontSize = 0)
{
Console.WriteLine("Set Current Font: " + font);
FontInfo before = new FontInfo
{
cbSize = Marshal.SizeOf<FontInfo>()
};
if (GetCurrentConsoleFontEx(ConsoleOutputHandle, false, ref before))
{
FontInfo set = new FontInfo
{
cbSize = Marshal.SizeOf<FontInfo>(),
FontIndex = 0,
FontFamily = FixedWidthTrueType,
FontName = font,
FontWeight = 400,
FontSize = fontSize > 0 ? fontSize : before.FontSize
};
// Get some settings from current font.
if (!SetCurrentConsoleFontEx(ConsoleOutputHandle, false, ref set))
{
var ex = Marshal.GetLastWin32Error();
Console.WriteLine("Set error " + ex);
throw new System.ComponentModel.Win32Exception(ex);
}
FontInfo after = new FontInfo
{
cbSize = Marshal.SizeOf<FontInfo>()
};
GetCurrentConsoleFontEx(ConsoleOutputHandle, false, ref after);
return new[] { before, set, after };
}
else
{
var er = Marshal.GetLastWin32Error();
Console.WriteLine("Get error " + er);
throw new System.ComponentModel.Win32Exception(er);
}
}
}
This way you can just do:
ConsoleHelper.SetCurrentFont("Consolas", 10);
After running the application (Ctrl + F5), right-click the title of the Console (it should say something like C:Windows\system32\cmd.exe) and select properties. Choose the "Font" tab, and you'll see the option to adjust the size.
The console does not support changing font size at runtime. A list of the available methods for modifying the current console windows settings can be found on MSDN. My understanding is that this is because:
The console is not a rich text interface, meaning it cannot display multiple fonts or font sizes.
as Noldorin states, this is something that should be up to the user, for example a person with vision problems may elect for a large fontsize.
I am writing a C# .NET app that accesses an USB device which exposes a serial port interface. I am using the handy .NET SerialPort class, which works just fine.
My problem is that I need to catch the DBT_DEVICEQUERYREMOVE event, but I don't get the event if I register using DBT_DEVTYP_DEVICEINTERFACE. I do get DBT_DEVICEARRIVAL and DBT_DEVICEREMOVECOMPLETE, but no DBT_DEVICEQUERYREMOVE.
From my web research it seems that I need to register using DBT_DEVTYP_HANDLE, which requires a handle, such as that returned by CreateFile. Since the SerialPort class does not expose this handle, I'm wondering if there is some other way to get the handle (or some other way to get the event of interest).
I think you could use a bit of reflection to get the handle, I don't know of a better way to get the handle that the .NET Framework is currently using. The SerialPort uses an internal type called SerialStream. This Stream has the handle you want. Since I don't have a serial port to test on, this code is a bit of a guesswork:
var serialPort = new SerialPort();
object stream = typeof(SerialPort).GetField("internalSerialStream", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(serialPort);
var handle = (SafeFileHandle)stream.GetType().GetField("_handle", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(stream);
This will give you a SafeFileHandle, which is a wrapper for handles. You could call DangerousGetHandle to get the actual IntPtr.
This handle only has a valid value after you call Open on the SerialPort, and becomes invalid when it's disposed. You should check the IsInvalid and IsClosed values of the handle first before using DangerousGetHandle.
What is also a solution is to grab the Serialport implementation of .Net and change it to your liking.
This is what I did for a project where I needed access to the handle, and because I had timing/async issues with SerialPort. So I boiled it down to the bear necessities.
public class SimpleSerialPort : IDisposable
{
private const uint GenericRead = 0x80000000;
private const uint GenericWrite = 0x40000000;
private const int OpenExisting = 3;
private const uint Setdtr = 5; // Set DTR high
private FileStream _fileStream;
public void Close()
{
Dispose();
}
public int WriteTimeout { get; set; }
public SafeFileHandle Handle { get; private set; }
public void Open(string portName, uint baudrate)
{
// Check if port can be found
bool isValid =
SerialPort.GetPortNames()
.Any(x => String.Compare(x, portName, StringComparison.OrdinalIgnoreCase) == 0);
if (!isValid)
{
throw new IOException(string.Format("{0} port was not found", portName));
}
string port = #"\\.\" + portName;
Handle = CreateFile(port, GenericRead | GenericWrite, 0, IntPtr.Zero, OpenExisting, 0, IntPtr.Zero);
if (Handle.IsInvalid)
{
throw new IOException(string.Format("{0} port is already open", portName));
}
var dcb = new Dcb();
// first get the current dcb structure setup
if (GetCommState(Handle, ref dcb) == false)
{
throw new IOException(string.Format("GetCommState error {0}", portName));
}
dcb.BaudRate = baudrate;
dcb.ByteSize = 8;
dcb.Flags = 129;
dcb.XoffChar = 0;
dcb.XonChar = 0;
/* Apply the settings */
if (SetCommState(Handle, ref dcb) == false)
{
throw new IOException(string.Format("SetCommState error {0}", portName));
}
/* Set DTR, some boards needs a DTR = 1 level */
if (EscapeCommFunction(Handle, Setdtr) == false)
{
throw new IOException(string.Format("EscapeCommFunction error {0}", portName));
}
// Write default timeouts
var cto = new Commtimeouts
{
ReadTotalTimeoutConstant = 500,
ReadTotalTimeoutMultiplier = 0,
ReadIntervalTimeout = 10,
WriteTotalTimeoutConstant = WriteTimeout,
WriteTotalTimeoutMultiplier = 0
};
if (SetCommTimeouts(Handle, ref cto) == false)
{
throw new IOException(string.Format("SetCommTimeouts error {0}", portName));
}
// Create filestream
_fileStream = new FileStream(Handle, FileAccess.ReadWrite, 32, false);
}
public void Write(byte[] bytes)
{
_fileStream.Write(bytes, 0, bytes.Length);
}
public void Read(byte[] readArray)
{
for (int read = 0; read < readArray.Length;)
{
read += _fileStream.Read(readArray, read, readArray.Length - read);
}
}
public byte ReadByte()
{
byte[] readsBytes = new byte[1];
Read(readsBytes);
return readsBytes[0];
}
public void Dispose()
{
if (Handle != null)
{
Handle.Dispose();
}
if (_fileStream != null)
{
_fileStream.Dispose();
}
_fileStream = null;
Handle = null;
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess, int dwShareMode,
IntPtr securityAttrs, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool GetCommState(
SafeFileHandle hFile, // handle to communications device
ref Dcb lpDcb // device-control block
);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool SetCommState(
SafeFileHandle hFile, // handle to communications device
ref Dcb lpDcb // device-control block
);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool EscapeCommFunction(
SafeFileHandle hFile, // handle to communications device
uint dwFunc
);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool SetCommTimeouts(
SafeFileHandle hFile, // handle to comm device
ref Commtimeouts lpCommTimeouts // time-out values
);
[StructLayout(LayoutKind.Sequential)]
private struct Commtimeouts
{
public int ReadIntervalTimeout;
public int ReadTotalTimeoutMultiplier;
public int ReadTotalTimeoutConstant;
public int WriteTotalTimeoutMultiplier;
public int WriteTotalTimeoutConstant;
}
[StructLayout(LayoutKind.Sequential)]
private struct Dcb
{
private readonly uint DCBlength;
public uint BaudRate;
public uint Flags;
private readonly ushort WReserved;
private readonly ushort XonLim;
private readonly ushort XoffLim;
public byte ByteSize;
private readonly byte Parity;
private readonly byte StopBits;
public byte XonChar;
public byte XoffChar;
private readonly byte ErrorChar;
private readonly byte EofChar;
private readonly byte EvtChar;
private readonly ushort WReserved1;
}
}
C# static constructor and GetVersion() any suggestions?
Hi,
I have defined struct like this in separate file OSVERSIONINFO.cs like this:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct OSVERSIONINFO
{
public static int SizeOf
{
get
{
return Marshal.SizeOf (typeof(OSVERSIONINFO));
}
}
public uint dwOSVersionInfoSize;
public uint dwMajorVersion;
public uint dwMinorVersion;
public uint dwBuildNumber;
public uint dwPlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string szCSDVersion;
}
Also I have this file OS.cs in which I have defined the following class:
public static class OS
{
static OS ()
{
OSVERSIONINFO info = new OSVERSIONINFO();
info.dwOSVersionInfoSize = (uint)OSVERSIONINFO.SizeOf;
if (!OS.GetVersion(ref info))
{
Console.WriteLine("Error!!!");
}
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetVersion (ref OSVERSIONINFO lpVersionInfo);
}
Way in static constructor of OS class population of info (instance of OSVERSIONINFO struct) fails?
If I call OS.GetVersion in other palce (not OS class) every thing is OK?
You should use the Environment.OSVersion.Platform property instead.
To answer the question, you need to call GetVersionEx.