Form does not work unless .Show() is called - c#

I have a form that represents a USB device Terminal that has been giving me some errors. After half a day of debugging strange errors with no known source I somehow found out that the Terminal does not function when it is instantiated but not shown. When I change the code and add usbTerminal.Show();, then it works properly.
USBTerminal usbTouchTerminal;
public MainForm()
{
InitializeComponent();
USBSettings usbTouchSettings = new USBSettings();
usbTouchTerminal = new USBTerminal(usbTouchSettings); //Create Terminal with settings
usbTouchTerminal.StartUSB();
usbTouchTerminal.Show(); //works ONLY when show is here
}
How is this possible and why? I've done a massive search and none of my code depends on the .Visible property on either my Terminal or main form?
I'm completely baffled on why some form would not work if it isn't shown. MSDN or google wasn't really a help either. I was certain it would function properly when instantiated but not shown.
PS. I added
usbTerminal.Show();
usbTerminal.Hide();
and the Terminal functioned correctly.
Thank you for any help!
EDIT:
I should also note that this usbTerminal uses the WndProc override. I'm not an expert on that, but I feel that it may have something to do with it.
I should note that this is LibUSBdotnet
public class USBSettings
{
/// <summary>
/// This is the Vender ID Number. (0x0B6A)
/// </summary>
public ushort VID { get; set; }
/// <summary>
/// This is the Product ID Number. (0x5346)
/// </summary>
public ushort PID { get; set; }
/// <summary>
/// This is the optional Serial Name. ("")
/// </summary>
public string SerialName { get; set; }
/// <summary>
/// This is the Reader USB Endpoint. (ReadEndpointID.Ep02)
/// </summary>
public ReadEndpointID ReaderEndpoint { get; set; }
/// <summary>
/// This is the Writer USB Endpoint. (WriteEndpointID.Ep01)
/// </summary>
public WriteEndpointID WriterEndpoint { get; set; }
/// <summary>
/// This is the Registry Key for USB settings. ("SOFTWARE\\DEFAULT\\USBPROPERTIES")
/// </summary>
public string SubKey { get; set; }
/// <summary>
/// This is the default read buffer size for the USB Device.
/// </summary>
public int ReadBufferSize { get; set; }
/// <summary>
/// This constructor houses default values for all properties.
/// </summary>
public USBSettings()
{
VID = 0x0B6A;
PID = 0x5346;
SerialName = "";
ReaderEndpoint = ReadEndpointID.Ep02;
WriterEndpoint = WriteEndpointID.Ep01;
SubKey = "SOFTWARE\\DEFAULT\\USBPROPERTIES";
ReadBufferSize = 100;
}
}

The question is poorly documented but this is fairly normal for code that works with devices. They tend to need to know about Plug & Play events and that requires a top-level window to be created that receives the WM_DEVICECHANGE notification message. Creating a .NET Form object isn't enough, you also have to create the native window for it. Which, in typical .NET lazy fashion, happens at the last possible moment, when you force the window to be visible. Either by calling the Show() method or setting the Visible property to true. The window doesn't actually have to be visible to get the Plug & Play notifications.
You can get the window created without also making it visible. That requires modifying the USBTerminal class. Paste this code:
protected override void SetVisibleCore(bool value) {
if (!this.IsHandleCreated) {
this.CreateHandle();
value = false;
}
base.SetVisibleCore(value);
}
And call the Show() method as normal. Beware that the Load event won't fire until the window actually becomes visible so if necessary move any code in the event handler to this method. If this is not the primary window for the app, in other words not the one that's passed to Application.Run() in your Main() method, then you can make do with simply calling this.CreateHandle() as the last statement in the form constructor. In which case calling Show() is no longer necessary.

I suspect this is because the underlying window is not created before you call Show(). Since the window isn't created, your custom WndProc isn't called.
To verify, you can create the window without showing it - by looking at the Handle property. As the documentation says - if the handle has not been created by the time you call, it will be created. Try it, I bet it'll work just as if you called Show and then Hide.

It is very hard to tell from the information you have but I think you are using a form where a class should be used. You should rethink your program structure and re-write this as a class to hold and transmit the data as you need. As some of the other have pointed out the listbox and/or other function are not running until the form is shown and the methods is executed.

Because some required functions will be called when Form onShow event called.

Related

Issue with EventHandler of a custom class

I am workin on a project that aims to interpret some parts of the finger alphabet. I am using a Kinect v1 to this end and these two projects: Lightbuzz.Vitruvius provides the main funcionality and Lightbuzz.Vitruvius.Fingertracking the ability to detect finger-tips (at least so far is the theory).
Plugging these two together was more tedious than challenging but the real challenge comes from an EventHandler. You see there is a HandController class where the fingers are detected and displayed. In this class is an EventHandler that kicks off the detection.
Having appropately changed every thing Rider now reports this error (I am using the .NET Framework 4.0):
<LightBuzz.Vitruvius>\HandsController.cs:1706 The type 'LightBuzz.Vitruvius.HandCollection' must be convertible to 'System.EventArgs' in order to use it as parameter 'TEventArgs' in the generic delegate 'void System.EventHandler<TEventArgs>(object, TEventArgs)'
The following is the EventHandler and the Code to be executed there on:
public event EventHandler<HandCollection> HandsDetected;
private void HandsController_HandsDetected(object sender, HandCollection e)
{
// Display the results!
if (e.HandLeft != null)
{
// Draw contour.
foreach (var point in e.HandLeft.ContourDepth)
{
kinectViewer.DrawEllipse(point, Brushes.Green, 2.0);
}
// Draw fingers.
foreach (var finger in e.HandLeft.Fingers)
{
kinectViewer.DrawEllipse(finger.DepthPoint, Brushes.White, 4.0);
}
}
if (e.HandRight != null)
{
// Draw contour.
foreach (var point in e.HandRight.ContourDepth)
{
kinectViewer.DrawEllipse(point, Brushes.Blue, 2.0);
}
// Draw fingers.
foreach (var finger in e.HandRight.Fingers)
{
kinectViewer.DrawEllipse(finger.DepthPoint, Brushes.White, 4.0);
}
}
}
// The object HandCollection is a seperate class as follows:
public partial class HandCollection
{
/// <summary>
/// The tracking ID of the current body.
/// </summary>
public int TrackingId { get; set; }
/// <summary>
/// The left hand data of the current body.
/// </summary>
public Hand HandLeft { get; set; }
/// <summary>
/// The right hand data of the current body.
/// </summary>
public Hand HandRight { get; set; }
}
My question would now be what does this error mean and how do I solve it? I have relatively few clues about the how and what of C#, so please be gentle. I have also found out that switching the framework to version 4.5 solves this issue but creates a dozen more.
As the error suggests, your HandCollection class cannot be used as a parameter in the eventhandler delegate. You might have your reasons for using .Net 4.0, so try making the class inherit from System.EventArgs and see if this works. Otherwise I would suggest switching framework.

Setting properties from another class

I want to pinpoint I'm totally new to C# and I'm just testing around to get a grasp of this language.
Want I want to achieve is to just console-print in a secondary window a couple of values I've set in the MainWindow.
This is a function contained in the MainWindow class, triggered by a button click.
private void ValidationExecuted(object sender, ExecutedRoutedEventArgs eventArgs)
{
// If the validation was successful, let's open a new window.
GeneratorWindow generatorWindow = new GeneratorWindow();
generatorWindow.TextBlockName1.Text = this.tbPoints.Text;
generatorWindow.TextBlockName2.Text = this.tbPDC.Text;
int.TryParse(this.tbPoints.Text, out int numberOfPoints);
int.TryParse(this.tbPDC.Text, out int pdc);
// Those lines correctly print the values I've inserted in the TextBoxes.
Console.WriteLine(numberOfPoints);
Console.WriteLine(pdc);
generatorWindow.NumberOfPoints = numberOfPoints;
generatorWindow.MainPDC = pdc;
generatorWindow.Show();
// Resetting the UI.
this.validator = new Validator();
this.grid.DataContext = this.validator;
eventArgs.Handled = true;
}
Now my secondary window:
public partial class GeneratorWindow : Window
{
/// <inheritdoc />
/// <summary>
/// Initializes a new instance of the <see cref="T:ABB_Rapid_Generator.GeneratorWindow" /> class.
/// </summary>
public GeneratorWindow()
{
this.InitializeComponent();
// Those lines just print a pair of 0.
Console.WriteLine(this.NumberOfPoints);
Console.WriteLine(this.MainPDC);
}
/// <summary>
/// Gets or sets the number of points.
/// </summary>
public int NumberOfPoints { private get; set; }
/// <summary>
/// Gets or sets the main PDC.
/// </summary>
public int MainPDC { private get; set; }
}
As you can see in the code comments, the Console.WriteLine() contained in the main class are correctly working. Moreover I can assign my custom values to the TextBlocks contained in the other class. On the contrary, the Console.WriteLine() lines in the secondary class are just outputting a couple of zeros.
What have I been missing?
The problem is that in GeneratorWindow you are writing to the console in the constructor method, so the values are being output before you are changing them.
The only way you can really get that output to work would be to pass the values as parameters of the constructor and set them (in the constructor) before you do the console output. Though there doesn't seem any logical reason to go down that path.
For example:
public GeneratorWindow(int numberOfPoints, int mainPdc)
{
this.InitializeComponent();
this.NumberOfPoints = numberOfPoints;
this.MainPDC = mainPdc;
Console.WriteLine(this.NumberOfPoints);
Console.WriteLine(this.MainPDC);
}
Alternatively, if you want to see the values after you set them, then you will need to move your console outputs to another function that you call after you have set the values.
For example, add this function to GeneratorWindow:
public void OutputValues()
{
Console.WriteLine(this.NumberOfPoints);
Console.WriteLine(this.MainPDC);
}
Which you can then call after you have set the values in your other class:
GeneratorWindow generatorWindow = new GeneratorWindow();
generatorWindow.NumberOfPoints = numberOfPoints;
generatorWindow.MainPDC = pdc;
generatorWindow.OutputValues();
you can add a parameter-ize constructor to do so
public partial class GeneratorWindow : Window
{
//Private members
int m_numberOfPoints;
int m_mainPDC;
/// <inheritdoc />
/// <summary>
/// Initializes a new instance of the <see cref="T:ABB_Rapid_Generator.GeneratorWindow" /> class.
/// </summary>
public GeneratorWindow(int mainPDC,int numberOfPoints)
{
this.InitializeComponent();
this.m_mainPDC = mainPDC;
this.m_numberOfPoints = numberOfPoints;
}
/// <summary>
/// Gets or sets the number of points.
/// </summary>
public int NumberOfPoints
{
get{ return m_numberOfPoints; }
set{ m_numberOfPoints = values; }
}
/// <summary>
/// Gets or sets the main PDC.
/// </summary>
public int MainPDC
{
get{ return m_mainPDC; }
set{ m_mainPDC= values; }
}
public void Print()
{
Console.WriteLine(this.NumberOfPoints);
Console.WriteLine(this.MainPDC);
}
}
also this is a constructor so it will be just called at
GeneratorWindow generatorWindow = new GeneratorWindow();//here
Change the secondary window call to
generatorWindow = new GeneratorWindow(pdc,numberOfPoints);
generatorWindow.Print();
Also, your code is not done in a good way IMO, why set values like this?
generatorWindow.TextBlockName1.Text = this.tbPoints.Text;
generatorWindow.TextBlockName2.Text = this.tbPDC.Text;
If you have private variables set just as above sample you can perform all converting, printing and , receiving console output in same class.you'll need to just call the constructor and print method.
Answer above is correct, but there is an alternative.
You can use setter methods like setNumberOfPoints, setMainPDC and print co console after setting the value. So in ValidationExecuted you call for a function to set variable, and in that function after setting variable you print it to console. But don't forget to remove printing to console from constructor

raising cross thread events in a DLL without a GUI in C#

I've written a DLL that does a bunch of stuff. One of the things it does is to search through a lot of incoming messages for a specific message, clean up the message, and raise an event when the message is found, and pass the data via the EventArgs.
Currently the DLL is working but the routine that searches for the message is slowing everything down and making the system slow to respond because there is so much data to go through.
I would like to move this searching to it's own thread, and once the message is found have it raise an event on the main thread and pass the message data to the main thread. I know how to make a thread to do the work, but I do not know how to make the thread raise the event on the main thread and pass the data to it. Could someone tell me how to do this, or point to an example of it?
I've tried creating a delegate and triggering an event, which works but when I try to pass the data I get a cross thread exception.
Some details that may be important. There most likely won't be a GUI at all and will probably remain a console application. Messages will always be coming in and the DLL has to continuously search them. The message the DLL is looking for may come as often as 1 couple times a second or it may be days between the messages.
Update for a real simple project illustrating what I would like to do. This code is rough cause I threw it together to test this out.
If you follow the code you will see that everything runs fine until the line in the CollectData function where:
StatusUpdated(this, null);
is called. At this point it causes the cross thread exception because of the UI thread and the data Collection thread. I know I can fix this by using an invoke on the UI thread, but as mentioned above this will most likely not be used with any sort of GUI (but it should be able to handle it). So the cross thread exception needs to be fixed in the BuildResultsManager class, I think in the function BRMgr_StatusUpdated. How do I get the data (in this case the value of currentVal) to the UI thread without changing any code in the MainWindow class.
You can run this by creating a solution with 2 projects, 1 for the first 2 files as a dll. The second as a wpf project, referencing the dll, and put a textbox named status on the form.
Main Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace BuildResultsManager
{
/// <summary>
/// Delegate to notify when data has changed
/// </summary>
/// <param name="sender">unused</param>
/// <param name="e">unused</param>
public delegate void StatusUpdatedEventHandler(object sender, EventArgs e);
/// <summary>
/// Connects to the PLC via PVI and reads in all the build results data, conditions it, updates values and reads/store into the database
/// </summary>
public class BuildResultsManager
{
#region events
// Change in The Build Results Manger Status
public event StatusUpdatedEventHandler StatusUpdated;
#endregion
#region Local variables
private Thread collectionThread;
private string statusMessage;
DataCollector dataCollection;
#endregion
#region Properties
/// <summary>
/// Current Status of the Build Results manager
/// </summary>
public String StatusMessage
{
get
{
return statusMessage;
}
private set
{
statusMessage = value;
if (StatusUpdated != null)
StatusUpdated(this, null);
}
}
#endregion
#region Constructors
/// <summary>
/// Default constructor
/// </summary>
public BuildResultsManager()
{
StatusMessage = "successfully initialized";
// start the thread that will collect all the data
dataCollection = new DataCollector();
dataCollection.StatusUpdated += new DCStatusUpdatedEventHandler(BRMgr_StatusUpdated);
collectionThread = new Thread(new ThreadStart(dataCollection.CollectData));
collectionThread.Start();
}
/// <summary>
/// EVent to handle updated status text
/// </summary>
/// <param name="sender">unused</param>
/// <param name="e">unused</param>
void BRMgr_StatusUpdated(object sender, EventArgs e)
{
StatusMessage = dataCollection.currentVal.ToString();
}
#endregion
}
}
The class that will be doing all of the thread work:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Windows.Threading;
using System.Threading;
namespace BuildResultsManager
{
/// <summary>
/// Delegate to notify when data has changed
/// </summary>
/// <param name="sender">unused</param>
/// <param name="e">unused</param>
public delegate void DCStatusUpdatedEventHandler(object sender, EventArgs e);
/// <summary>
/// Handles all of the data collection and conditioning
/// </summary>
class DataCollector
{
#region events
// Change in The Build Results Manger Status
public event DCStatusUpdatedEventHandler StatusUpdated;
#endregion
private const long updateInterval = 1000;
private Stopwatch updateTimer;
public int currentVal;
#region local variables
private bool shouldStop;
#endregion
/// <summary>
/// Default Constructor
/// </summary>
public DataCollector()
{
shouldStop = false;
updateTimer = new Stopwatch();
updateTimer.Start();
}
/// <summary>
/// Main task that listens for new data and collects it when it's available
/// </summary>
public void CollectData()
{
currentVal = 5;
while (!shouldStop && currentVal < 10)
{
if(updateTimer.ElapsedMilliseconds > updateInterval)
{
currentVal++;
if (StatusUpdated != null)
{
StatusUpdated(this, null);
}
//reset the timer
updateTimer.Restart();
}
}
}
/// <summary>
/// Asks the thread to stop
/// </summary>
public void RequestStop()
{
shouldStop = true;
}
}
}
Code behind for the wpf project:
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
#region Local variables
private string BRMgrStatus;
private BuildResultsManager.BuildResultsManager BRMgr;
#endregion
public MainWindow()
{
InitializeComponent();
// create an instance of the build manager
BRMgr = new BuildResultsManager.BuildResultsManager();
if(BRMgr != null)
{
status.Text = BRMgr.StatusMessage;
BRMgr.StatusUpdated += new StatusUpdatedEventHandler(BRMgr_StatusUpdated);
}
}
/// <summary>
/// EVent to handle updated status text
/// </summary>
/// <param name="sender">unused</param>
/// <param name="e">unused</param>
void BRMgr_StatusUpdated(object sender, EventArgs e)
{
BuildResultsManager.BuildResultsManager brm;
brm = (BuildResultsManager.BuildResultsManager)sender;
status.Text = brm.StatusMessage;
}
}
If you don't use a GUI there's no need to execute things on the same thread, just protect non-thread-safe resources with a locking mechanism (lock, mutex, etc) to avoid concurrent access and you're good.

Caliburn.Micro nested ViewModels best practice

This is a pretty long question, so please bear with me.
Currently I am developing a small tool intended to help me keep track of the myriad of characters in my Stories.
The tool does the following:
Load the characters which are currently stored as json on the disk and stores them in a list, which is presented in the Shell via a ListBox.
If the user then opens a character the Shell, which is a Conductor<Screen>.Collection.OneActive, opens a new CharacterViewModel, that derives from Screen.
The Character gets the Character that is going to be opened via the IEventAggregator message system.
The CharacterViewModel furthermore has various properties which are sub ViewModels which bind to various sub Views.
And here is my Problem:
Currently I initialize the sub ViewModels manually when the ChracterViewModel is initialized. But this sounds fishy to me and I am pretty sure there is a better way to do this, but I cannot see how I should do it.
Here is the code of the CharacterViewModel:
/// <summary>ViewModel for the character view.</summary>
public class CharacterViewModel : Screen, IHandle<DataMessage<ICharacterTagsService>>
{
// --------------------------------------------------------------------------------------------------------------------
// Fields
// -------------------------------------------------------------------------------------------------------------------
/// <summary>The event aggregator.</summary>
private readonly IEventAggregator eventAggregator;
/// <summary>The character tags service.</summary>
private ICharacterTagsService characterTagsService;
// --------------------------------------------------------------------------------------------------------------------
// Constructors & Destructors
// -------------------------------------------------------------------------------------------------------------------
/// <summary>Initializes a new instance of the <see cref="CharacterViewModel"/> class.</summary>
public CharacterViewModel()
{
if (Execute.InDesignMode)
{
this.CharacterGeneralViewModel = new CharacterGeneralViewModel();
this.CharacterMetadataViewModel = new CharacterMetadataViewModel();
}
}
/// <summary>Initializes a new instance of the <see cref="CharacterViewModel"/> class.</summary>
/// <param name="eventAggregator">The event aggregator.</param>
[ImportingConstructor]
public CharacterViewModel(IEventAggregator eventAggregator)
: this()
{
this.eventAggregator = eventAggregator;
this.eventAggregator.Subscribe(this);
}
// --------------------------------------------------------------------------------------------------------------------
// Properties
// -------------------------------------------------------------------------------------------------------------------
/// <summary>Gets or sets the character.</summary>
public Character Character { get; set; }
/// <summary>Gets or sets the character general view model.</summary>
public CharacterGeneralViewModel CharacterGeneralViewModel { get; set; }
/// <summary>Gets or sets the character metadata view model.</summary>
public CharacterMetadataViewModel CharacterMetadataViewModel { get; set; }
/// <summary>Gets or sets the character characteristics view model.</summary>
public CharacterApperanceViewModel CharacterCharacteristicsViewModel { get; set; }
/// <summary>Gets or sets the character family view model.</summary>
public CharacterFamilyViewModel CharacterFamilyViewModel { get; set; }
// --------------------------------------------------------------------------------------------------------------------
// Methods
// -------------------------------------------------------------------------------------------------------------------
/// <summary>Saves a character to the file system as a json file.</summary>
public void SaveCharacter()
{
ICharacterSaveService saveService = new JsonCharacterSaveService(Constants.CharacterSavePathMyDocuments);
saveService.SaveCharacter(this.Character);
this.characterTagsService.AddTags(this.Character.Metadata.Tags);
this.characterTagsService.SaveTags();
}
/// <summary>Called when initializing.</summary>
protected override void OnInitialize()
{
this.CharacterGeneralViewModel = new CharacterGeneralViewModel(this.eventAggregator);
this.CharacterMetadataViewModel = new CharacterMetadataViewModel(this.eventAggregator, this.Character);
this.CharacterCharacteristicsViewModel = new CharacterApperanceViewModel(this.eventAggregator, this.Character);
this.CharacterFamilyViewModel = new CharacterFamilyViewModel(this.eventAggregator);
this.eventAggregator.PublishOnUIThread(new CharacterMessage
{
Data = this.Character
});
base.OnInitialize();
}
/// <summary>
/// Handles the message.
/// </summary>
/// <param name="message">The message.</param>
public void Handle(DataMessage<ICharacterTagsService> message)
{
this.characterTagsService = message.Data;
}
}
For Completion Sake I also give you one of the sub ViewModels. The others a of no importance because they are structured the same way, just perform different tasks.
/// <summary>The character metadata view model.</summary>
public class CharacterMetadataViewModel : Screen
{
/// <summary>The event aggregator.</summary>
private readonly IEventAggregator eventAggregator;
/// <summary>Initializes a new instance of the <see cref="CharacterMetadataViewModel"/> class.</summary>
public CharacterMetadataViewModel()
{
if (Execute.InDesignMode)
{
this.Character = DesignData.LoadSampleCharacter();
}
}
/// <summary>Initializes a new instance of the <see cref="CharacterMetadataViewModel"/> class.</summary>
/// <param name="eventAggregator">The event aggregator.</param>
/// <param name="character">The character.</param>
public CharacterMetadataViewModel(IEventAggregator eventAggregator, Character character)
{
this.Character = character;
this.eventAggregator = eventAggregator;
this.eventAggregator.Subscribe(this);
}
/// <summary>Gets or sets the character.</summary>
public Character Character { get; set; }
/// <summary>
/// Gets or sets the characters tags.
/// </summary>
public string Tags
{
get
{
return string.Join("; ", this.Character.Metadata.Tags);
}
set
{
char[] delimiters = { ',', ';', ' ' };
List<string> tags = value.Split(delimiters, StringSplitOptions.RemoveEmptyEntries).ToList();
this.Character.Metadata.Tags = tags;
this.NotifyOfPropertyChange(() => this.Tags);
}
}
}
I already read in on Screens, Conductors and Composition, IResult and Coroutines and skimmed the rest of the Documentation, but somehow I cannot find what I am looking for.
//edit: I should mention the code I have works just fine. I'm just not satisfied with it, since I think I am not understanding the concept of MVVM quite right and therefore make faulty code.
There is nothing wrong with having one ViewModel instantiate several child ViewModels. If you're building a larger or more complex application, it's pretty much unavoidable if you want to keep your code readable and maintainable.
In your example, you are instantiating all four child ViewModels whenever you create an instance of CharacterViewModel. Each of the child ViewModels takes IEventAggregator as a dependency. I would suggest that you treat those four child ViewModels as dependencies of the primary CharacterViewModel and import them through the constructor:
[ImportingConstructor]
public CharacterViewModel(IEventAggregator eventAggregator,
CharacterGeneralViewModel generalViewModel,
CharacterMetadataViewModel metadataViewModel,
CharacterAppearanceViewModel appearanceViewModel,
CharacterFamilyViewModel familyViewModel)
{
this.eventAggregator = eventAggregator;
this.CharacterGeneralViewModel generalViewModel;
this.CharacterMetadataViewModel = metadataViewModel;
this.CharacterCharacteristicsViewModel = apperanceViewModel;
this.CharacterFamilyViewModel = familyViewModel;
this.eventAggregator.Subscribe(this);
}
You can thus make the setters on the child ViewModel properties private.
Change your child ViewModels to import IEventAggregator through constructor injection:
[ImportingConstructor]
public CharacterGeneralViewModel(IEventAggregator eventAggregator)
{
this.eventAggregator = eventAggregator;
}
In your example, two of those child ViewModels are passed an instance of the Character data in their constructors, implying a dependency. In these cases, I would give each child ViewModel a public Initialize() method where you set the Character data and activate the event aggregator subscription there:
public Initialize(Character character)
{
this.Character = character;
this.eventAggregator.Subscribe(this);
}
Then call this method in your CharacterViewModel OnInitialize() method:
protected override void OnInitialize()
{
this.CharacterMetadataViewModel.Initialize(this.Character);
this.CharacterCharacteristicsViewModel.Initialize(this.Character);
this.eventAggregator.PublishOnUIThread(new CharacterMessage
{
Data = this.Character
});
base.OnInitialize();
}
For the child ViewModels where you're only updating the Character data through the EventAggregator, leave the this.eventAggregator.Subscribe(this) call in the constructor.
If any of your child ViewModels are not actually required for the page to function, you could initialize those VM properties via property import:
[Import]
public CharacterGeneralViewModel CharacterGeneralViewModel { get; set; }
Property imports don't occur until after the constructor has completed running.
I would also suggest handling the instantiation of ICharacterSaveService through constructor injection as well, rather than explicitly creating a new instance every time you save data.
The primary purpose of MVVM was to allow front-end designers to work on the layout of the UI in a visual tool (Expression Blend) and coders to implement the behavior and business without interfering with one another. The ViewModel exposes data to be bound to the view, describes the view's behavior at an abstract level, and frequently acts as a mediator to the back-end services.
There is no one "correct" way to do it, and there are situations where it isn't the best solution. There are times when the best solution is to toss the extra layer of abstraction of using a ViewModel and just write some code-behind. So while it's a great structure for your application as a whole, don't fall into the trap of forcing everything to fit into the MVVM pattern. If you have a few more graphically complex user controls where it simply works better to have some code-behind, then that's what you should do.

C#: How to make a form remember its Bounds and WindowState (Taking dual monitor setups into account)

I have made a class which a form can inherit from and it handles form Location, Size and State. And it works nicely. Except for one thing:
When you maximize the application on a different screen than your main one, the location and size (before you maximized) gets stored correctly, but when it is maximized (according to its previous state) it is maximized on my main monitor. When I then restore it to normal state, it goes to the other screen where it was before. When I then maximize it again, it of course maximized on the correct screen.
So my question is... how can I make a form, when it is maximized, remember what screen it was maximized on? And how do I restore that when the form opens again?
Kind of complete solution to problem
I accepted the answer which had a very good tip about how to if on screen. But that was just part of my problem, so here is my solution:
On load
First get stored Bounds and WindowState from whatever storage.
Then set the Bounds.
Make sure Bounds are visible either by Screen.AllScreens.Any(ø => ø.Bounds.IntersectsWith(Bounds)) or MdiParent.Controls.OfType<MdiClient>().First().ClientRectangle.IntersectsWith(Bounds).
If it doesn't, just do Location = new Point();.
Then set window state.
On closing
Store WindowState.
If WindowState is FormWindowState.Normal, then store Bounds, otherwise store RestoreBounds.
And thats it! =)
Some example code
So, as suggested by Oliver, here is some code. It needs to be fleshed out sort of, but this can be used as a start for whoever wants to:
PersistentFormHandler
Takes care of storing and fetching the data somewhere.
public sealed class PersistentFormHandler
{
/// <summary>The form identifier in storage.</summary>
public string Name { get; private set; }
/// <summary>Gets and sets the window state. (int instead of enum so that it can be in a BI layer, and not require a reference to WinForms)</summary>
public int WindowState { get; set; }
/// <summary>Gets and sets the window bounds. (X, Y, Width and Height)</summary>
public Rectangle WindowBounds { get; set; }
/// <summary>Dictionary for other values.</summary>
private readonly Dictionary<string, Binary> otherValues;
/// <summary>
/// Instantiates new persistent form handler.
/// </summary>
/// <param name="windowType">The <see cref="Type.FullName"/> will be used as <see cref="Name"/>.</param>
/// <param name="defaultWindowState">Default state of the window.</param>
/// <param name="defaultWindowBounds">Default bounds of the window.</param>
public PersistentFormHandler(Type windowType, int defaultWindowState, Rectangle defaultWindowBounds)
: this(windowType, null, defaultWindowState, defaultWindowBounds) { }
/// <summary>
/// Instantiates new persistent form handler.
/// </summary>
/// <param name="windowType">The <see cref="Type.FullName"/> will be used as base <see cref="Name"/>.</param>
/// <param name="id">Use this if you need to separate windows of same type. Will be appended to <see cref="Name"/>.</param>
/// <param name="defaultWindowState">Default state of the window.</param>
/// <param name="defaultWindowBounds">Default bounds of the window.</param>
public PersistentFormHandler(Type windowType, string id, int defaultWindowState, Rectangle defaultWindowBounds)
{
Name = string.IsNullOrEmpty(id)
? windowType.FullName
: windowType.FullName + ":" + id;
WindowState = defaultWindowState;
WindowBounds = defaultWindowBounds;
otherValues = new Dictionary<string, Binary>();
}
/// <summary>
/// Looks for previously stored values in database.
/// </summary>
/// <returns>False if no previously stored values were found.</returns>
public bool Load()
{
// See Note 1
}
/// <summary>
/// Stores all values in database
/// </summary>
public void Save()
{
// See Note 2
}
/// <summary>
/// Adds the given <paramref key="value"/> to the collection of values that will be
/// stored in database on <see cref="Save"/>.
/// </summary>
/// <typeparam key="T">Type of object.</typeparam>
/// <param name="key">The key you want to use for this value.</param>
/// <param name="value">The value to store.</param>
public void Set<T>(string key, T value)
{
// Create memory stream
using (var s = new MemoryStream())
{
// Serialize value into binary form
var b = new BinaryFormatter();
b.Serialize(s, value);
// Store in dictionary
otherValues[key] = new Binary(s.ToArray());
}
}
/// <summary>
/// Same as <see cref="Get{T}(string,T)"/>, but uses default(<typeparamref name="T"/>) as fallback value.
/// </summary>
/// <typeparam name="T">Type of object</typeparam>
/// <param name="key">The key used on <see cref="Set{T}"/>.</param>
/// <returns>The stored object, or the default(<typeparamref name="T"/>) object if something went wrong.</returns>
public T Get<T>(string key)
{
return Get(key, default(T));
}
/// <summary>
/// Gets the value identified by the given <paramref name="key"/>.
/// </summary>
/// <typeparam name="T">Type of object</typeparam>
/// <param name="key">The key used on <see cref="Set{T}"/>.</param>
/// <param name="fallback">Value to return if the given <paramref name="key"/> could not be found.
/// In other words, if you haven't used <see cref="Set{T}"/> yet.</param>
/// <returns>The stored object, or the <paramref name="fallback"/> object if something went wrong.</returns>
public T Get<T>(string key, T fallback)
{
// If we have a value with this key
if (otherValues.ContainsKey(key))
{
// Create memory stream and fill with binary version of value
using (var s = new MemoryStream(otherValues[key].ToArray()))
{
try
{
// Deserialize, cast and return.
var b = new BinaryFormatter();
return (T)b.Deserialize(s);
}
catch (InvalidCastException)
{
// T is not what it should have been
// (Code changed perhaps?)
}
catch (SerializationException)
{
// Something went wrong during Deserialization
}
}
}
// Else return fallback
return fallback;
}
}
Note 1: In the load method you have to look for previously stored WindowState, WindowBounds and other values. We use SQL Server, and have a Window table with columns for Id, Name, MachineName (for Environment.MachineName), UserId, WindowState, X, Y, Height, Width. So for every window, you would have one row with WindowState, X, Y, Height and Width for each user and machine. In addition we have a WindowValues table which just has a foreign key to WindowId, a Key column of type String and a Value column of type Binary. If there is stuff that is not found, I just leave things default and return false.
Note 2: In the save method you then, of course do the reverse from what you do in the Load method. Creating rows for Window and WindowValues if they don't exist already for the current user and machine.
PersistentFormBase
This class uses the previous class and forms a handy base class for other forms.
// Should have been abstract, but that makes the the designer crash at the moment...
public class PersistentFormBase : Form
{
private PersistentFormHandler PersistenceHandler { get; set; }
private bool handlerReady;
protected PersistentFormBase()
{
// Prevents designer from crashing
if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
{
Load += persistentFormLoad;
FormClosing += persistentFormFormClosing;
}
}
protected event EventHandler<EventArgs> ValuesLoaded;
protected event EventHandler<EventArgs> StoringValues;
protected void StoreValue<T>(string key, T value)
{
if (!handlerReady)
throw new InvalidOperationException();
PersistenceHandler.Set(key, value);
}
protected T GetValue<T>(string key)
{
if (!handlerReady)
throw new InvalidOperationException();
return PersistenceHandler.Get<T>(key);
}
protected T GetValue<T>(string key, T fallback)
{
if (!handlerReady)
throw new InvalidOperationException();
return PersistenceHandler.Get(key, fallback);
}
private void persistentFormLoad(object sender, EventArgs e)
{
// Create PersistenceHandler and load values from it
PersistenceHandler = new PersistentFormHandler(GetType(), (int) FormWindowState.Normal, Bounds);
PersistenceHandler.Load();
handlerReady = true;
// Set size and location
Bounds = PersistenceHandler.WindowBounds;
// Check if we have an MdiParent
if(MdiParent == null)
{
// If we don't, make sure we are on screen
if (!Screen.AllScreens.Any(ø => ø.Bounds.IntersectsWith(Bounds)))
Location = new Point();
}
else
{
// If we do, make sure we are visible within the MdiClient area
var c = MdiParent.Controls.OfType<MdiClient>().FirstOrDefault();
if(c != null && !c.ClientRectangle.IntersectsWith(Bounds))
Location = new Point();
}
// Set state
WindowState = Enum.IsDefined(typeof (FormWindowState), PersistenceHandler.WindowState) ? (FormWindowState) PersistenceHandler.WindowState : FormWindowState.Normal;
// Notify that values are loaded and ready for getting.
var handler = ValuesLoaded;
if (handler != null)
handler(this, EventArgs.Empty);
}
private void persistentFormFormClosing(object sender, FormClosingEventArgs e)
{
// Set common things
PersistenceHandler.WindowState = (int) WindowState;
PersistenceHandler.WindowBounds = WindowState == FormWindowState.Normal ? Bounds : RestoreBounds;
// Notify that values will be stored now, so time to store values.
var handler = StoringValues;
if (handler != null)
handler(this, EventArgs.Empty);
// Save values
PersistenceHandler.Save();
}
}
And thats pretty much it. To use it, a form would just inherit from the PersistentFormBase. That would automatically take care of bounds and state. If anything else should be stored, like a splitter distance, you would listen for the ValuesLoaded and StoringValues events and in those use the GetValue and StoreValue methods.
Hope this can help someone! Please let me know if it does. And also, please provide some feedback if there is anything you think could be done better or something. I would like to learn =)
There's no built in way to do this - you'll have to write the logic yourself. One reason for this is that you have to decide how to handle the case where the monitor that the window was last shown on is no longer available. This can be quite common with laptops and projectors, for example. The Screen class has some useful functionality to help with this, although it can be difficult to uniquely and consistently identify a display.
I found a solution to your problem by writing a little functio, that tests, if a poitn is on a connected screen.
The main idea came from
http://msdn.microsoft.com/en-us/library/system.windows.forms.screen(VS.80).aspx
but some modifications were needed.
public static bool ThisPointIsOnOneOfTheConnectedScreens(Point thePoint)
{
bool FoundAScreenThatContainsThePoint = false;
for(int i = 0; i < Screen.AllScreens.Length; i++)
{
if(Screen.AllScreens[i].Bounds.Contains(thePoint))
FoundAScreenThatContainsThePoint = true;
}
return FoundAScreenThatContainsThePoint;
}
There are a few issues with the above solution.
On multiple screens as well as if the restore screen is smaller.
It should use Contains(...), rather than IntersectsWith as the control part of the form might otherwise be outside the screen-area.
I will suggest something along these lines
bool TestBounds(Rectangle R) {
if (MdiParent == null) return Screen.AllScreens.Any(ø => ø.Bounds.Contains(R)); // If we don't have an MdiParent, make sure we are entirely on a screen
var c = MdiParent.Controls.OfType<MdiClient>().FirstOrDefault(); // If we do, make sure we are visible within the MdiClient area
return (c != null && c.ClientRectangle.Contains(R));
}
and used like this. (Note that I let Windows handle it if the saved values does not work)
bool BoundsOK=TestBounds(myBounds);
if (!BoundsOK) {
myBounds.Location = new Point(8,8); // then try (8,8) , to at least keep the size, if other monitor not currently present, or current is lesser
BoundsOK = TestBounds(myBounds);
}
if (BoundsOK) { //Only change if acceptable, otherwise let Windows handle it
StartPosition = FormStartPosition.Manual;
Bounds = myBounds;
WindowState = Enum.IsDefined(typeof(FormWindowState), myWindowState) ? (FormWindowState)myWindowState : FormWindowState.Normal;
}
Try to spawn your main form in its saved location in restored (non-maximized) state, THEN maximize it if the last state was maximized.
As Stu said, be careful about removed monitors in this case. Since the saved location may contain off-screen coordinates (even negative ones), you may effectively end up with and invisible (off-screen, actually) window. I think checking for desktop bounds before loading previous state should prevent this.

Categories

Resources