How to get all monospaced fonts in Windows? - c#

I've seen How do I get all installed fixed-width fonts?, but I can't make it work:
internal class NativeMethods
{
public const Int32 LF_FACESIZE = 32;
public const Int32 FIXED_PITCH = 1;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class LOGFONT
{
public Int32 lfHeight = 0;
public Int32 lfWidth = 0;
public Int32 lfEscapement = 0;
public Int32 lfOrientation = 0;
public Int32 lfWeight = 0;
public Byte lfItalic = 0;
public Byte lfUnderline = 0;
public Byte lfStrikeOut = 0;
public Byte lfCharSet = 0;
public Byte lfOutPrecision = 0;
public Byte lfClipPrecision = 0;
public Byte lfQuality = 0;
public Byte lfPitchAndFamily = 0;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = LF_FACESIZE)]
public String lfFaceName = string.Empty;
}
}
public partial class MainForm : Form
{
private string font_names = null;
public MainForm()
{
InitializeComponent();
StringBuilder sb = new StringBuilder();
foreach (var font_family in FontFamily.Families)
{
if (font_family.IsStyleAvailable(FontStyle.Regular))
{
var lf = new NativeMethods.LOGFONT();
Font font = new Font(font_family, 9.0f);
font.ToLogFont(lf);
if ((lf.lfPitchAndFamily & 0x3) == NativeMethods.FIXED_PITCH)
{
sb.AppendLine(font_family.Name);
}
}
}
font_names = sb.ToString();
}
private void MainForm_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawString(font_names, SystemFonts.MessageBoxFont, SystemBrushes.WindowText, 10.0f, 10.0f);
}
}
It seem no matter what font it is, the lfPitchAndFamily is always zero.
So how get all monospaced fonts?

I think I'll just use P/Invoke to do this:
internal class NativeMethods
{
public const Int32 LF_FACESIZE = 32;
public const Int32 LF_FULLFACESIZE = 64;
public const Int32 DEFAULT_CHARSET = 1;
public const Int32 FIXED_PITCH = 1;
public const Int32 TRUETYPE_FONTTYPE = 0x0004;
public delegate Int32 FONTENUMPROC(ref ENUMLOGFONT lpelf, ref NEWTEXTMETRIC lpntm, UInt32 FontType, IntPtr lParam);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct LOGFONT
{
public Int32 lfHeight;
public Int32 lfWidth;
public Int32 lfEscapement;
public Int32 lfOrientation;
public Int32 lfWeight;
public Byte lfItalic;
public Byte lfUnderline;
public Byte lfStrikeOut;
public Byte lfCharSet;
public Byte lfOutPrecision;
public Byte lfClipPrecision;
public Byte lfQuality;
public Byte lfPitchAndFamily;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = LF_FACESIZE)]
public String lfFaceName;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct TEXTMETRIC
{
public Int32 tmHeight;
public Int32 tmAscent;
public Int32 tmDescent;
public Int32 tmInternalLeading;
public Int32 tmExternalLeading;
public Int32 tmAveCharWidth;
public Int32 tmMaxCharWidth;
public Int32 tmWeight;
public Int32 tmOverhang;
public Int32 tmDigitizedAspectX;
public Int32 tmDigitizedAspectY;
public Char tmFirstChar;
public Char tmLastChar;
public Char tmDefaultChar;
public Char tmBreakChar;
public Byte tmItalic;
public Byte tmUnderlined;
public Byte tmStruckOut;
public Byte tmPitchAndFamily;
public Byte tmCharSet;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct ENUMLOGFONT
{
public LOGFONT elfLogFont;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = LF_FULLFACESIZE)]
public String elfFullName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = LF_FACESIZE)]
public String elfStyle;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct NEWTEXTMETRIC
{
public Int32 tmHeight;
public Int32 tmAscent;
public Int32 tmDescent;
public Int32 tmInternalLeading;
public Int32 tmExternalLeading;
public Int32 tmAveCharWidth;
public Int32 tmMaxCharWidth;
public Int32 tmWeight;
public Int32 tmOverhang;
public Int32 tmDigitizedAspectX;
public Int32 tmDigitizedAspectY;
public Char tmFirstChar;
public Char tmLastChar;
public Char tmDefaultChar;
public Char tmBreakChar;
public Byte tmItalic;
public Byte tmUnderlined;
public Byte tmStruckOut;
public Byte tmPitchAndFamily;
public Byte tmCharSet;
public UInt32 ntmFlags;
public UInt32 ntmSizeEM;
public UInt32 ntmCellHeight;
public UInt32 ntmAvgWidth;
}
[DllImport("gdi32.dll", CharSet = CharSet.Auto)]
public extern static Int32 EnumFontFamiliesEx(IntPtr hdc, ref LOGFONT lpLogfont, FONTENUMPROC lpEnumFontFamExProc, IntPtr lParam, UInt32 dwFlags);
}
internal static class Program
{
private static void Main()
{
Graphics graphics = Graphics.FromHwnd(IntPtr.Zero);
IntPtr hdc = graphics.GetHdc();
var logfont = new NativeMethods.LOGFONT() { lfCharSet = NativeMethods.DEFAULT_CHARSET };
NativeMethods.EnumFontFamiliesEx(hdc, ref logfont, new NativeMethods.FONTENUMPROC(EnumFontFamExProc), IntPtr.Zero, 0);
graphics.ReleaseHdc();
}
private static int EnumFontFamExProc(ref NativeMethods.ENUMLOGFONT lpelf, ref NativeMethods.NEWTEXTMETRIC lpntm, uint FontType, IntPtr lParam)
{
if ((lpelf.elfLogFont.lfPitchAndFamily & 0x3) == NativeMethods.FIXED_PITCH)
{
Console.WriteLine(lpelf.elfLogFont.lfFaceName);
}
return 1;
}
}

Related

CS0308 Marshal.SizeOf<> error, how do I fix that?

I have error in this code:
intPtr = Marshal.AllocHGlobal(Marshal.SizeOf<Win32API.OBJECT_BASIC_INFORMATION>(object_BASIC_INFORMATION));
Win32API.NtQueryObject(zero, 0, intPtr, Marshal.SizeOf<Win32API.OBJECT_BASIC_INFORMATION>(object_BASIC_INFORMATION), ref num);
object_BASIC_INFORMATION = (Win32API.OBJECT_BASIC_INFORMATION)Marshal.PtrToStructure(intPtr, object_BASIC_INFORMATION.GetType());
Marshal.FreeHGlobal(intPtr);
intPtr2 = Marshal.AllocHGlobal(object_BASIC_INFORMATION.TypeInformationLength);
num = object_BASIC_INFORMATION.TypeInformationLength;
This line:
intPtr = Marshal.AllocHGlobal(Marshal.SizeOf<Win32API.OBJECT_BASIC_INFORMATION>(object_BASIC_INFORMATION));
What am I doing wrong?
OBJECT_BASIC_INFORMATION:
public struct OBJECT_BASIC_INFORMATION
{
public int Attributes;
public int GrantedAccess;
public int HandleCount;
public int PointerCount;
public int PagedPoolUsage;
public int NonPagedPoolUsage;
public int Reserved1;
public int Reserved2;
public int Reserved3;
public int NameInformationLength;
public int TypeInformationLength;
public int SecurityDescriptorLength;
public System.Runtime.InteropServices.ComTypes.FILETIME CreateTime;
}
Error:
CS0308 C# The non-generic method cannot be used with type arguments

c# - After changing screen resolution the cursor hover area is offset

I have the below code to change my 2nd display screen resolution. It all works fine and changes as expected. However once it has been changed my mouse/cursor is offset. eg the active location is not where the pointer shows on the screen.
Thoughts?
using System;
using System.Windows;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;
[StructLayout(LayoutKind.Sequential)]
public struct DEVMODE1
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string dmDeviceName;
public short dmSpecVersion;
public short dmDriverVersion;
public short dmSize;
public short dmDriverExtra;
public int dmFields;
public short dmOrientation;
public short dmPaperSize;
public short dmPaperLength;
public short dmPaperWidth;
public short dmScale;
public short dmCopies;
public short dmDefaultSource;
public short dmPrintQuality;
public short dmColor;
public short dmDuplex;
public short dmYResolution;
public short dmTTOption;
public short dmCollate;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string dmFormName;
public short dmLogPixels;
public short dmBitsPerPel;
public int dmPelsWidth;
public int dmPelsHeight;
public int dmPosition;
public int dmDisplayFlags;
public int dmDisplayFrequency;
public int dmICMMethod;
public int dmICMIntent;
public int dmMediaType;
public int dmDitherType;
public int dmReserved1;
public int dmReserved2;
public int dmPanningWidth;
public int dmPanningHeight;
};
class User_32
{
[DllImport("user32.dll")]
public static extern int EnumDisplaySettings(string deviceName, int modeNum, ref DEVMODE1 devMode);
[DllImport("user32.dll")]
public static extern int ChangeDisplaySettings(ref DEVMODE1 devMode, int flags);
[DllImport("user32.dll")]
public static extern int ChangeDisplaySettingsEx(string lpszDeviceName, ref DEVMODE1 lpDevMode, IntPtr hwnd, ChangeDisplaySettingsFlags dwflags, IntPtr lParam);
public const int ENUM_CURRENT_SETTINGS = -1;
public const int CDS_UPDATEREGISTRY = 0x01;
public const int CDS_TEST = 0x02;
public const int DISP_CHANGE_SUCCESSFUL = 0;
public const int DISP_CHANGE_RESTART = 1;
public const int DISP_CHANGE_FAILED = -1;
[Flags()]
public enum ChangeDisplaySettingsFlags : uint{
CDS_NONE = 0,
CDS_UPDATEREGISTRY = 0x00000001,
CDS_TEST = 0x00000002,
CDS_FULLSCREEN = 0x00000004,
CDS_GLOBAL = 0x00000008,
CDS_SET_PRIMARY = 0x00000010,
CDS_VIDEOPARAMETERS = 0x00000020,
CDS_ENABLE_UNSAFE_MODES = 0x00000100,
CDS_DISABLE_UNSAFE_MODES = 0x00000200,
CDS_RESET = 0x40000000,
CDS_RESET_EX = 0x20000000,
CDS_NORESET = 0x10000000
}
}
namespace Resolution
{
class CResolution
{
public CResolution(int iWidth, int iHeight)
{
DEVMODE1 dm = new DEVMODE1();
dm.dmFormName = new String(new char[32]);
dm.dmSize = (short)Marshal.SizeOf(dm);
dm.dmPosition = 2;
if (0 != User_32.EnumDisplaySettings(null, User_32.ENUM_CURRENT_SETTINGS, ref dm))
{
dm.dmPelsWidth = iWidth;
dm.dmPelsHeight = iHeight;
long result = User_32.ChangeDisplaySettingsEx("\\\\.\\DISPLAY2", ref dm, IntPtr.Zero, User_32.ChangeDisplaySettingsFlags.CDS_UPDATEREGISTRY, IntPtr.Zero);
}
}
}
}
-
static void Main(string[] args)
{
Resolution.CResolution ChangeRes = new Resolution.CResolution(2560, 1600);
}

Dropbox folder download issue (c#)

I'm automaticly downloading a whole folder from my Dropbox - storage(?), via the weblink eg:https://www.dropbox.com/sh/bunchOfLetters/somthnsomthn?dl=1 with just a basic webclient:
using (WebClient wc = new WebClient())
{
wc.DownloadFile(new Uri(uri), _basePath + localPath);
}
The folder naturaly comes as a .rar file (due to Dropbox's download system), and if i try to open the file manualy (via Winrar) there is no problem at all. Now comes the problem.... if i try to use any kind of automated libary (like unrar or SharpCompress) it always gives my a 'Corupted Header' as if the download wouldnt have gotten everythng or the file just broke ..but still opening it with Winrar works just fine.
If anyone has an idea how and why; i would be greatfull to hear your thoughts.
Edit:
here is the function i use for SharpCompress:
public static bool ExtractToFolder(string extractionPackage, string outputPath)
{
if (extractionPackage == null) throw new ArgumentNullException(nameof(extractionPackage));
if (outputPath == null) throw new ArgumentNullException(nameof(outputPath));
if (string.IsNullOrEmpty(extractionPackage))
throw new ArgumentException("Argument is null or empty", nameof(extractionPackage));
if (string.IsNullOrEmpty(outputPath))
throw new ArgumentException("Argument is null or empty", nameof(outputPath));
if (!extractionPackage.EndsWith(".rar")) throw new InvalidDataException("not a .rar File");
Directory.CreateDirectory(outputPath);
try
{
using (Stream stream = File.OpenRead(extractionPackage))
using (RarReader reader = RarReader.Open(stream))
{
while (reader.MoveToNextEntry())
{
reader.WriteEntryToDirectory(outputPath, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
}
}
return true;
}
catch
{
return false;
}
}
and if someone is interested in the unrar one:
..i know its not well done but it still works for normal files...just not Dropbox ones
namespace Cryptus.Rar
{
/// <summary>
/// just for compatibility purposes, use <see cref="SharpCompress"/>
/// </summary>
public class Unrar
{
public enum RarOperations
{
OP_EXTRACT = 0,
OP_TEST = 1,
OP_LIST = 2
}
public const int ERAR_END_ARCHIVE = 10;
public const int ERAR_NO_MEMORY = 11;
public const int ERAR_BAD_DATA = 12;
public const int ERAR_BAD_ARCHIVE = 13;
public const int ERAR_UNKNOWN_FORMAT = 14;
public const int ERAR_EOPEN = 15;
public const int ERAR_ECREATE = 16;
public const int ERAR_ECLOSE = 17;
public const int ERAR_EREAD = 18;
public const int ERAR_EWRITE = 19;
public const int ERAR_SMALL_BUF = 20;
public const int RAR_OM_LIST = 0;
public const int RAR_OM_EXTRACT = 1;
public const int RAR_SKIP = 0;
public const int RAR_TEST = 1;
public const int RAR_EXTRACT = 2;
public const int RAR_VOL_ASK = 0;
public const int RAR_VOL_NOTIFY = 1;
[DllImport("unrar.dll")]
public static extern IntPtr RAROpenArchive(ref RAROpenArchiveData ArchiveData);
[DllImport("unrar.dll")]
public static extern int RARCloseArchive(IntPtr hArcData);
[DllImport("unrar.dll")]
public static extern int RARReadHeader(IntPtr hArcData, ref RARHeaderData HeaderData);
[DllImport("unrar.dll")]
public static extern IntPtr RAROpenArchiveEx(ref RAROpenArchiveDataEx ArchiveData);
[DllImport("unrar.dll")]
public static extern int RARReadHeaderEx(IntPtr hArcData, ref RARHeaderDataEx HeaderData);
[DllImport("unrar.dll")]
public static extern int RARProcessFile(IntPtr hArcData, int Operation, string DestPath, string DestName);
[DllImport("unrar.dll")]
public static extern int RARGetDllVersion();
[DllImport("user32.dll")]
private static extern bool CharToOem(string lpszSrc, [Out] StringBuilder lpszDst);
/// <summary>
/// opens an arcive and unloads its content to destDolder
/// </summary>
/// <param name="strFileName">input .rar File</param>
/// <param name="destFolder">destination Folder</param>
public void UnloadArchieve(string strFileName, string destFolder)
{
IntPtr lHandle;
int iStatus;
RAROpenArchiveData uRAR = new RAROpenArchiveData();
RARHeaderData uHeader = new RARHeaderData();
uRAR.ArcName = strFileName + char.MinValue;
uRAR.OpenMode = RAR_OM_EXTRACT;
uRAR.CmtBuf = null;
string ExtractDir = Path.GetDirectoryName(strFileName);
StringBuilder sbDir = new StringBuilder();
CharToOem(destFolder, sbDir);
lHandle = RAROpenArchive(ref uRAR);
if (uRAR.OpenResult != 0)
Console.Write("Unable to open the Archieve!!!");
while (RARReadHeader(lHandle, ref uHeader) == 0)
{
int result = RARProcessFile(lHandle, 2, sbDir.ToString(), null);
if (0 != result)
Console.Write("Unable to open the Archieve!!!");
}
iStatus = RARCloseArchive(lHandle);
}
[StructLayout(LayoutKind.Sequential)]
public struct RARHeaderData
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string ArcName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string FileName;
public uint Flags;
public uint PackSize;
public uint UnpSize;
public uint HostOS;
public uint FileCRC;
public uint FileTime;
public uint UnpVer;
public uint Method;
public uint FileAttr;
public string CmtBuf;
public uint CmtBufSize;
public uint CmtSize;
public uint CmtState;
}
[StructLayout(LayoutKind.Sequential)]
public struct RAROpenArchiveData
{
public string ArcName;
public uint OpenMode;
public uint OpenResult;
public string CmtBuf;
public uint CmtBufSize;
public uint CmtSize;
public uint CmtState;
}
[StructLayout(LayoutKind.Sequential)]
public struct RAROpenArchiveDataEx
{
public string ArcName;
public string ArcNameW;
public uint OpenMode;
public uint OpenResult;
public string CmtBuf;
public uint CmtBufSize;
public uint CmtSize;
public uint CmtState;
public uint Flags;
public uint Reserved;
}
[StructLayout(LayoutKind.Sequential)]
public struct RARHeaderDataEx
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string ArcName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string FileName;
public string FileNameW;
public uint Flags;
public uint PackSize;
public uint PackSizeHigh;
public uint UnpSize;
public uint UnpSizeHigh;
public uint HostOS;
public uint FileCRC;
public uint FileTime;
public uint UnpVer;
public uint Method;
public uint FileAttr;
public string CmtBuf;
public uint CmtBufSize;
public uint CmtSize;
public uint CmtState;
public uint Reserved;
}
}
Ok so it seems that #smarx was right with his comment! Its a bit strange, but Dropbox generates .rar files which contain not a rar, but a zip header. This is no problem for any form of automatic detection of the header format, but if you use a rar extraction method (which should be used for .rar files..) it wont work.

Switch between Landscape and Portrait mode in two screens

I can switch between Landsacpe and Portrait mode in one screen by using the following code (That I have done this morning). And the problem is I have two screens in a computer. And I want the screen 1 is LANDSCAPE mode, and the screen 2 is PORTRAIT mode. But I don't know how to modify the code to make it work. (Sorry about my English)
class ModeSetting
{
public const int LANDSCAPE = 0;
public const int PORTRAIT = 1;
public static bool ChangeMode(int screenID, int modeID)
{
//I'm not using screenID here. Let me know how to do that. How to get screenID
//Or anything that help me.
DEVMODE dm = new DEVMODE();
dm.dmDeviceName = new string(new char[32]);
dm.dmFormName = new string(new char[32]);
//dm.dmSize = Marshal.SizeOf(dm);
if (modeID != PORTRAIT) modeID = LANDSCAPE;
if (0 != NativeMethods.EnumDisplaySettings(
null,
NativeMethods.ENUM_CURRENT_SETTINGS,
ref dm))
{
int temp = dm.dmPelsHeight;
dm.dmPelsHeight = dm.dmPelsWidth;
dm.dmPelsWidth = temp;
dm.dmDisplayOrientation = modeID;
int iRet = NativeMethods.ChangeDisplaySettings(ref dm, 0);
Console.WriteLine(iRet);
if (NativeMethods.DISP_CHANGE_SUCCESSFUL != iRet)
{
return false;
}
return true;
}
return false;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct DEVMODE
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string dmDeviceName;
public short dmSpecVersion;
public short dmDriverVersion;
public short dmSize;
public short dmDriverExtra;
public int dmFields;
public int dmPositionX;
public int dmPositionY;
public int dmDisplayOrientation;
public int dmDisplayFixedOutput;
public short dmColor;
public short dmDuplex;
public short dmYResolution;
public short dmTTOption;
public short dmCollate;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string dmFormName;
public short dmLogPixels;
public short dmBitsPerPel;
public int dmPelsWidth;
public int dmPelsHeight;
public int dmDisplayFlags;
public int dmDisplayFrequency;
public int dmICMMethod;
public int dmICMIntent;
public int dmMediaType;
public int dmDitherType;
public int dmReserved1;
public int dmReserved2;
public int dmPanningWidth;
public int dmPanningHeight;
}
internal class NativeMethods
{
// PInvoke declaration for EnumDisplaySettings Win32 API
[DllImport("user32.dll", CharSet = CharSet.Ansi)]
public static extern int EnumDisplaySettings(
string lpszDeviceName,
int iModeNum,
ref DEVMODE lpDevMode);
// PInvoke declaration for ChangeDisplaySettings Win32 API
[DllImport("user32.dll", CharSet = CharSet.Ansi)]
public static extern int ChangeDisplaySettings(
ref DEVMODE lpDevMode,
int dwFlags);
// constants
public const int ENUM_CURRENT_SETTINGS = -1;
public const int DMDO_DEFAULT = 0;
public const int DMDO_90 = 1;
public const int DMDO_180 = 2;
public const int DMDO_270 = 3;
public const int DISP_CHANGE_SUCCESSFUL = 0;
}
}
And I can switch between LANDSCAPE and PORTRAIT mode by using:
ModeSetting.ChangeMode(0, ModeSetting.LANDSCAPE);//0 here is screen ID that I cannot do when two screens
ModeSetting.ChangeMode(0, ModeSetting.PORTRAIT);

How to create partition on hdd using IOCTL_DISK_SET_DRIVE_LAYOUT on C#

I need to implement an hdd partitioning program using c#.
Below is part of my code.
I think it works because it returns true value from DeviceIOcontrol with no errors, but the problem is my program doesn't show anything.
I got a lot of help from Medo's home page, MSDN, and pinvoke site.
public static bool partitionDisk(string path)
{
var signature = new byte[4];
System.Security.Cryptography.RandomNumberGenerator.Create().GetBytes(signature);
using (SafeFileHandle handle = NativeMethods2.CreateFile(path, (NativeMethods2.FILE_SHARE_READ|NativeMethods.GENERIC_READ ) | (NativeMethods.GENERIC_WRITE | NativeMethods2.FILE_SHARE_WRITE), 0, IntPtr.Zero, NativeMethods2.OPEN_EXISTING, 0, IntPtr.Zero))
{
if (handle.IsInvalid) { throw new Win32Exception(); }
var newdi = new NativeMethods2.DRIVE_LAYOUT_INFORMATION_EX();
newdi.PartitionStyle = NativeMethods2.PARTITION_STYLE.PARTITION_STYLE_MBR;
newdi.PartitionCount = 4;
newdi.DriveLayoutInformaiton.Mbr.Signature = BitConverter.ToInt32(signature, 0);
newdi.PartitionEntry = new NativeMethods2.PARTITION_INFORMATION_EX[0x16];
newdi.PartitionEntry[0] = new NativeMethods2.PARTITION_INFORMATION_EX();
newdi.PartitionEntry[0].PartitionStyle = NativeMethods2.PARTITION_STYLE.PARTITION_STYLE_MBR;
newdi.PartitionEntry[0].StartingOffset = 1048576; // check by diskpart
newdi.PartitionEntry[0].PartitionLength = 0xFFFFFFFFFFfffff; //int64 max
newdi.PartitionEntry[0].PartitionNumber = 1;
newdi.PartitionEntry[0].RewritePartition = true;
newdi.PartitionEntry[0].DriveLayoutInformaiton.Mbr.BootIndicator = false;
newdi.PartitionEntry[0].DriveLayoutInformaiton.Mbr.HiddenSectors = 0; //sector size
newdi.PartitionEntry[0].DriveLayoutInformaiton.Mbr.PartitionType = 0x07;// PARTITION_IFS (NTFS partition or logical drive)
newdi.PartitionEntry[0].DriveLayoutInformaiton.Mbr.RecognizedPartition = true;
for (int k = 2; k < newdi.PartitionCount; k++)
{
newdi.PartitionEntry[k] = new NativeMethods2.PARTITION_INFORMATION_EX();
newdi.PartitionEntry[k].DriveLayoutInformaiton.Mbr.BootIndicator = false;
newdi.PartitionEntry[k].DriveLayoutInformaiton.Mbr.HiddenSectors = 0;
newdi.PartitionEntry[k].PartitionLength = 0;
newdi.PartitionEntry[k].PartitionNumber = k;
newdi.PartitionEntry[k].DriveLayoutInformaiton.Mbr.PartitionType = 0;
newdi.PartitionEntry[k].DriveLayoutInformaiton.Mbr.RecognizedPartition = false;
newdi.PartitionEntry[k].RewritePartition = true;
newdi.PartitionEntry[k].StartingOffset = 0;
}
Int32 bytesOut = 0;
if (NativeMethods2.DeviceIoControl(handle, NativeMethods2.IOCTL_DISK_SET_DRIVE_LAYOUT, ref newdi, Marshal.SizeOf(newdi), IntPtr.Zero, 0, ref bytesOut, IntPtr.Zero) == false) { throw new Win32Exception(); }
}
}
private static class NativeMethods2
{
public const int GENERIC_READ = -2147483648;
public const int GENERIC_WRITE = 1073741824;
public const int OPEN_EXISTING = 3;
public const int FILE_SHARE_READ = 0x0000000001;
public const int FILE_SHARE_WRITE = 0x0000000002;
public const int IOCTL_DISK_UPDATE_PROPERTIES = 0x70140;
public const int IOCTL_DISK_SET_DRIVE_LAYOUT_EX = 0x7C054;
public enum PARTITION_STYLE
{
PARTITION_STYLE_MBR = 0,
PARTITION_STYLE_GPT = 1,
PARTITION_STYLE_RAW = 2,
}
[StructLayout(LayoutKind.Sequential)]
public struct DRIVE_LAYOUT_INFORMATION_EX
{
public PARTITION_STYLE PartitionStyle;
public int PartitionCount;
public DRIVE_LAYOUT_INFORMATION_UNION DriveLayoutInformaiton;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 0x16)]
public PARTITION_INFORMATION_EX[] PartitionEntry;
}
[StructLayout(LayoutKind.Sequential)]
public struct PARTITION_INFORMATION_EX
{
public PARTITION_STYLE PartitionStyle;
public long StartingOffset;
public long PartitionLength;
public int PartitionNumber;
public bool RewritePartition;
public PARTITION_INFORMATION_UNION DriveLayoutInformaiton;
}
[StructLayout(LayoutKind.Sequential)]
public struct PARTITION_INFORMATION_MBR
{
public byte PartitionType;
public bool BootIndicator;
public bool RecognizedPartition;
public Int32 HiddenSectors;
}
[StructLayout(LayoutKind.Sequential)]
public struct PARTITION_INFORMATION_GPT
{
public Guid PartitionType; //GUID
public Guid PartitionId; //GUID
public Int64 Attributes;
public char[] Name;
}
[StructLayout(LayoutKind.Sequential)]
public struct PARTITION_INFORMATION
{
public long StartingOffset;
public long PartitionLength;
public int HiddenSectors;
public int PartitionNumber;
public byte PartitionType;
[MarshalAs(UnmanagedType.I1)]
public bool BootIndicator;
[MarshalAs(UnmanagedType.I1)]
public bool RecognizedPartition;
[MarshalAs(UnmanagedType.I1)]
public bool RewritePartition;
}
[StructLayout(LayoutKind.Explicit)]
public struct DRIVE_LAYOUT_INFORMATION_UNION
{
[FieldOffset(0)]
public DRIVE_LAYOUT_INFORMATION_MBR Mbr;
[FieldOffset(0)]
public DRIVE_LAYOUT_INFORMATION_GPT Gpt;
}
[StructLayout(LayoutKind.Sequential)]
public struct DRIVE_LAYOUT_INFORMATION_MBR
{
public Int32 Signature;
}
[StructLayout(LayoutKind.Sequential)]
public struct DRIVE_LAYOUT_INFORMATION_GPT
{
public Guid DiskId;
public Int64 StartingUsableOffset;
public Int64 UsableLength;
public ulong MaxPartitionCount;
}
[StructLayout(LayoutKind.Explicit)]
public struct PARTITION_INFORMATION_UNION
{
[FieldOffset(0)]
public PARTITION_INFORMATION_MBR Mbr;
[FieldOffset(0)]
public PARTITION_INFORMATION_GPT Gpt;
}
[DllImportAttribute("kernel32.dll", EntryPoint = "CreateFileW", SetLastError = true)]
public static extern SafeFileHandle CreateFile([MarshalAsAttribute(UnmanagedType.LPWStr)] string lpFileName, Int32 dwDesiredAccess, Int32 dwShareMode, IntPtr lpSecurityAttributes, Int32 dwCreationDisposition, Int32 dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImportAttribute("kernel32.dll", EntryPoint = "DeviceIoControl", SetLastError = true)]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern Boolean DeviceIoControl(SafeFileHandle hDevice, Int32 dwIoControlCode, ref DRIVE_LAYOUT_INFORMATION_EX lpInBuffer, int nInBufferSize, IntPtr lpOutBuffer, Int32 nOutBufferSize, ref Int32 lpBytesReturned, IntPtr lpOverlapped);
}
private static class NativeMethods
{
public const int GENERIC_READ = -2147483648;
public const int GENERIC_WRITE = 1073741824;
public const int OPEN_EXISTING = 3;
public const int IOCTL_DISK_CREATE_DISK = 0x7C058;
public enum PARTITION_STYLE
{
PARTITION_STYLE_MBR = 0,
PARTITION_STYLE_GPT = 1,
PARTITION_STYLE_RAW = 2,
}
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct CREATE_DISK
{
public PARTITION_STYLE PartitionStyle;
public CREATE_DISK_UNION_MBR_GPT MbrGpt;
}
[StructLayoutAttribute(LayoutKind.Explicit)]
public struct CREATE_DISK_UNION_MBR_GPT
{
[FieldOffset(0)]
public CREATE_DISK_MBR Mbr;
[FieldOffset(0)]
public CREATE_DISK_GPT Gpt;
}
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct CREATE_DISK_MBR
{
public Int32 Signature;
}
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct CREATE_DISK_GPT
{
public Guid DiskId;
public Int32 MaxPartitionCount;
}
[DllImportAttribute("kernel32.dll", EntryPoint = "CreateFileW", SetLastError = true)]
public static extern SafeFileHandle CreateFile([MarshalAsAttribute(UnmanagedType.LPWStr)] string lpFileName, Int32 dwDesiredAccess, Int32 dwShareMode, IntPtr lpSecurityAttributes, Int32 dwCreationDisposition, Int32 dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImportAttribute("kernel32.dll", EntryPoint = "DeviceIoControl", SetLastError = true)]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern Boolean DeviceIoControl(SafeFileHandle hDevice, Int32 dwIoControlCode, ref CREATE_DISK lpInBuffer, int nInBufferSize, IntPtr lpOutBuffer, Int32 nOutBufferSize, ref Int32 lpBytesReturned, IntPtr lpOverlapped);
}
...and to call the function:
DiskIO.partitionDisk("//./PHYSICALDRIVE2")

Categories

Resources