I presume you’re doing this for some sort of config system right?
If so… what I would do, is if the config file doesn’t already exist, set it up with the default values you want, but when it comes to stuff related to display mode, make sure that the default values are what the user has set in their system.
You can get that information with the GraphicsAdapter.DefaultAdapter.CurrentDisplayMode
property.
Be sure to create a CUSTOM C# object to store the relevant information. You shouldn’t directly serialize a DisplayMode
. For example, if you’re just storing resolution:
public class MyConfigObject
{
public int Width { get; set; }
public int Height { get; set; }
}
That’ll be what you (de)serialize.
So, to create the config file:
//Create a default config object to store resolution settings
var config = new MyConfigObject
{
Width = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width,
Height = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height
};
//Serialize to JSON
string json = JsonConvert.SerializeObject(config);
//Do whatever with that string to save to disk or wherever you plan to store it.
Then, when loading it in:
//Deserialize the config JSON
var config = JsonConvert.DeserializeObject<MyConfigObject>(json);
//Retrieve resolution info
int w = config.Width;
int h = Config.Height;
//Do whatever you plan to do with said info
//For example...set the game's preferred backbuffer size.
//You'd do this somewhere in Game1.cs.
graphicsDevice.PreferredBackBufferWidth = w;
graphicsDevice.PreferredBackBufferHeight = h;
graphicsDevice.ApplyChanges();
But there is a flaw with that code. It doesn’t check that the display mode in the config file is actually supported by the system. So, I could for example go into the config and set the width/height to some outrageously big numbers and break your game.
To fix that, right after retrieving the config values for the display mode, check them to see if they match anything in GraphicsAdapter.DefaultAdapter.SupportedDisplayModes
. You can use LINQ for that. If you don’t get any matching display mode, reset the config values for the display mode to the system default (like you did when you created the file), then save to disk and apply.
For example:
//Right after retrieving config values and before applying, check if the display mode is supported.
var supportedModeMatch = GraphicsAdapter.DefaultAdapter.SupportedDisplayModes.FirstOrDefault(x=>x.Width == width && x.Height == height);
//That LINQ query will search the list for the first element where that lambda expression evaluates to true. AKA: the first display mode with a Width and Height matching the config values.
//
//If it doesn't find any, it will return null.
if(supportedModeMatch == null)
{
//Reset config values, save, then apply them.
}
else
{
//Just apply 'em! You're good to go.
}
That should help ya. No need to serialize GraphicsAdapter
directly.