VC++ calling a Paint event into a button event - winforms

I'm making a Windows form in VC++ and I've found tons of material talking about how to call Paint events into other functions or events, however those tend to be in C# and that doesn't seem to work for me or they don't explain the actual syntax of the code for me to understand. I'm still learning the more detailed aspects of programming so just telling me to use Validate() doesn't do me much good.
private: System::Void Stand_wheel_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e)
I have my Paint event. That has if statements that read if certain criteria are met to change the points that are used in the painting.
private: System::Void button3_Click_1(System::Object^ sender, System::EventArgs^ e)
And my button to click that I want to trigger the painting. I have tried using the Stand_wheel_Paint name and it is fraught with errors. I've tried almost everything to my knowledge to get it under the event in the button and I just can't. I also know that I have to 'erase' the old paint and redo the current work but from what I have found tends to almost get me there but is from C#. I would love any help that someone could offer.
using ( // <- I get an error on this parantheses
var g = Graphics.FromImage(Stand_wheel.Image))
{
e->Graphics->DrawLines(pen, points);
Stand_wheel.Refresh();
}
This looks close to a solution but still has errors.

The using block exists only in C#, a necessity because it doesn't have deterministic destruction. C++/CLI, like standard C++, does. If you declare a variable of a ref class type, rather than a tracking handle, its Dispose method will be automatically called when the variable goes out of scope.
No using needed, and the C++/CLI approach is much more powerful than the C# one. For example, C++/CLI deterministic destruction works with class member data as easily as locals.

Related

How to initialize a view model with properties from another view Model

My question is what is the ideal way to initialize child window in WPF, MVVM way?
I have a WPF window , let's call it as ParentWindow having its view Model class - ParentWindowViewModel. On click of a button on the ParentWindow UI , I launch a new WPF window - ChildWindow like below
ChildWindow r = new ChildWindow ();
r.ShowDialog();
r.WindowStartupLocation = WindowStartupLocation.CenterScreen;
Now, the ChildWindow has its own viewModel like - ChildWindowViewModel. The Child Window has the datacontext set in its xaml as
<Window.DataContext>
<viewModel:ChildWindowViewModel/>
</Window.DataContext>
On Click of button in the ParentWindow, When i Launch the Child Window, I need to pass certain values to the Child Window, which will be used to initialize the Child Window. Without these values the child window cannot be initialized.Every time I click the button to Launch the child window, the values being passed to child window will differ based on some other selected items in the Parent Window.
I would do something like this (without error checking):
in ParentWindow.xaml.cs
private void Some_Event_In_Parent_Window()
{
ParentWindowViewModel pvm = DataContext as ParentWindowViewModel;
ChildWindow cw = new ChildWindow(pvm.Element1, pvm.Element2);
}
int ChildWindow.xaml.cs
public ChildWindow(bool elem1, string elem2)
{
InitializeComponents();
DataContext = new ChildWindowViewModel(elem1, elem2);
}
If you are dealing with minimal elements that need to be transferred between windows/VM's, and it is mainly about sending some form of "state" or "value", then there isnt too much issue with initializing the Viewmodel in the code behind. Remember that the <viewmodel:ChildWindowViewModel/> is equivalent to DataContext = new ChildWindowViewModel() in your code behind. While yes, you can create spaghetti code, or confusing dependencies by not adhering to patterns; you can also over engineer the crap of something that did not require the effort and can be just as confusing.
I find that there is an obsession with keeping your code behind empty (i have the same obsession). Remember, that the Code behind is there for a reason, and you CAN use it. Sometimes it isnt worth over-complicating your code base by implementing some big pattern if you have a single one off requirement that can be handled in code behind with some added comments.
Aside from Event Handlers, I utilize the Code Behind for these main use cases:
There is an adjustment needed to the UI that is too complicated to handle in the XAML alone. Example: I need a weird string concatenation and logic of some inputted text fields.
There is some minimal state or data needed to be transferred between Views. (Like your requirement)
There is some sort of logic that needs to happen that is UI specific and not related to the underlying data or ViewModel. (This is rare, and almost always a small one off).
In terms of "is this ideal" for MVVM; it depends on your definition of ideal.
Can this be handled by some other design pattern? Probably...? But is it worth it.
Does implementing said pattern add bloat or overhead that only solves a small problem? Maybe. That is for you to decide.
Are you going to be repeating this implementation more than once? If so you may have some bad design to rethink.
Does implementing this solution of using Code behind solve your issue in a speedy way, that is moderately maintainable and readable? If so, then I wouldnt see a problem.
Ideal is not always defined by rules. It is also specific to your needs and requirements.
It isnt always easy to determine where your use case should be handled. View, ViewModel, maybe a Service, or a Singleton state class.
If your use case is this one window, Code behind is fine (In my opinion). If you are doing this for 20 windows, you may want a Service to maintain the state somehow. Think of it more - if your code is SOLID and DRY

Visual Studio "Not Responding" when I change a datetimepicker value in Winforms [duplicate]

I have a datetimepicker in C#. When I click on it, it expands to show a monthly calendar, when I click the left arrow to go back a month, it changes the value and calls my event. The event includes too much code to include here but it calls several functions needless to say.
The problem I'm having is that when I click that left arrow it gets stuck in some sort of loop and keeps descending through the months and I can't stop it. One of the functions that is being called contains a Application.DoEvents() and if I comment that out it doesn't get stuck in the loop, but I need that command to update another section of the interface. Any idea why this is happening?
I can duplicate it sometimes with this code, sometimes it just does it a couple times, sometimes it gets stuck in the loop.
private void DateTimePickerValueChangedEvent(object sender, EventArgs e)
{
afunction();
}
private void afunction()
{
listView1.Clear();
panel1.Visible = true;
Application.DoEvents();
}
I also have the same problem. In my case, instead of calling DoEvents I'm updating a Crystal Report view. The only workaround I found is to update my view upon the CloseUp event instead of ValueChanged or TextChanged.
Scott, how did you finally corrected your problem ?
The DateTimePicker ValueChanged event is buggy. Per Microsoft Windows Forms Team on this page https://connect.microsoft.com/VisualStudio/feedback/details/1290685/debugging-datetimepicker-event-hangs-vs:
"The DateTimePicker control installs a mouse hook as part of its functionality, but when the debugger has the WinForms application stopped on a breakpoint, it allows the possibility of a deadlock if VS happens to get a mouse message. For now, the deadlock is unfortunately a consequence of the DateTimePicker's design. The mouse hook is installed when the drop down is clicked to display the calendar. This means that breakpoints should not be sent in any event handlers which would be called while the calendar is active. We are currently investigating whether it is possible to address this issue and we will update this thread with further information if we are able to make a fix available."
Without seeing any of the code, try these steps:
Comment out the entire event handler
to see how fast it runs with nothing
attached to it.
Uncomment lines one at a time to see
which ones are causing the most
problems.
Analyze those method calls.
...
Profit!
You could try a couple of things. Get rid of the DoEvents inside of the ChangedEvent.
Call the doevents inside of a seperate function after maybe a period of time (thread.sleep() ?).
I know doevents does cause issues but I rarely use it.
event procedure ValueChanged :
set parameter in sender.tag
enableTimer and execute parameter using sender.tag
example:
private void DateTimePicker_ValueChanged(object sender, EventArgs e)
{
DateTimePicker ThisSender = (DateTimePicker)sender;
Timer.Tag = ThisSender.Name.ToString() + "=" + ThisSender.Value;
Timer.Enabled = true;
}

How to do Drag and Drop in WPF between two lists?

I'm having a hard time solving an issue of mine, I'm literally going mad.
Here's the idea: I have two ListView elements, and I need to open a dialogue when an element drops from the first list onto the second, but I need both the information from the element being dropped and the element being added to fill in the dialogue.
The thing is, I can't even get the basic functionality right - and that is opening the dialogue on drop.
I'm going to learn the D&D technique from start to finish, but I quickly need a way to at least call the dialogue.
After writing and erasing some code the only thing I have left is the following:
private void lvListaRadnika_MouseDown(object sender, MouseButtonEventArgs e)
{
DragDrop.DoDragDrop(lvListaRadnika, presenter.Selected, DragDropEffects.None);
}
private void ListView_Drop(object sender, DragEventArgs e)
{
DodavanjeRezervacije dr = new DodavanjeRezervacije(new DodavanjeRezervacijePresenter(null,true));
dr.Show();
}
At this point I need something to happen and after that I'll see about adding all the necessary checks, feeding the dialogue with the data as well as adding an adorner.
If someone could explain as much as possible about drag and drop along the way I would highly appreciate it, but at this point I only really need this to fire up.
Converting my comment into an answer:
You should really give a try to the Gong WPF Drag And Drop Framework. I helps do these kind of things in a really clean and nice (MVVM) way.
I had answered a similar question where i have a sample project demo to drag drop between any two controls.
Just refer to the answer here and you can use that control.

MVVM: commands vs eventhandlers

I know this has been done to death, but most answers are along the lines of "yeah, you can use eventhandlers in place of commands if you like". This still doesn't solve the problem of whether writing complicated commands is warranted vs just wiring up eventhandlers in code behind to call testable methods in your view model.
I don't like commands because they produce a lot of boilerplate code and don't give me any benefit over normal methods, plus some of them (such as drag & drop) are a pain to implement.
What's wrong with writing:
codebehind:
private void Button_Click(object sender, RoutedEventArgs e)
{
viewModel.LoadData();
}
viewmodel:
public void LoadData()
{
//....
}
This is equally testable (if not more) as any command is. IMO, as long as UI specific stuff isn't leaking into your business logic, there's really no need to waste time on complicated patterns like that. Thoughts?
What's wrong with writing
Nothing - for the most part.
There is nothing wrong with using code behind, if you are careful to keep the business logic out of the code behind file. This is delegating this directly to the ViewModel, which is reasonable.
That being said, there are a couple of potential downfalls here in terms of long term maintainability:
By doing this, you're coupling the View to the ViewModel more tightly. While this is a reasonable thing to do (the View, in reality, always knows about the ViewModel), it does prevent potential reuse of View components in some scenarios, as using an ICommand allows you to have the same View be used with potentially different ViewModels. (This is rare in practice, however.)
This starts a slippery slope - by adding "any" code into code behind, you're opening up the potential that another developer will add "just one more line" in there. Over time, this can lead to a mess.
It's adding code into another place that has to be maintained. Now you'll have to maintain the ViewModel .cs file, your .xaml file, and the code behind file.
You're hard-wiring this logic into a Button. If you decide to change controls, use a gesture, etc., you'll have to remember to rework this logic.
I was in your boat at first, I even asked basically the same question here. But I came around and came to really like commands.
Some commands really are complex enough in and of themselves to warrant testing. They are just as testable as anything else on your viewmodel.
ICommand also includes CanExecute and CanExecuteChanged, which enables your view to intelligently enable/disable itself pretty much for free. This is fantastic in complex views.
Commands make it easier to change your view around, most controls have a Command property you can bind to, and simply moving the binding around is easier than mucking with event handlers. This is especially true if you have designers working on the XAML.
You can pretty much write the entire logic of the view without the view even existing. It leads to a nice flow of build the meat all at once, then throw the interface on top all at once.
Keeping your code in one place leads to longer term maintainability.
To me a very important argument against events is forcing the UI Designer to write code to be able to test a View. And worse: every time he redesigns the View he has to rewire the events.
Commands and the behaviors in Blend make render this process obsolete and much easier.
Another problem might arise when actually using the event arguments when writing the event handler. When you want to switch to another control or another event you might have become very dependent on the event arguments making it hard to switch because the other control/event does not support the same event arguments.

What causes a window to not appear in the taskbar until it's Alt-Tabbed to in Vista?

When our app is started programatically (either through custom action in MSI installer or when starting a new instance) in Windows Vista (also happens in Windows 7 Beta) it won't appear in the taskbar and isn't focused. Alt-tabbing to it will make it appear in the taskbar properly and stay there.
What causes this? I've seen this in some other apps before as well, but not sure why. Out app is .NET WinForms app. Never see this happen in XP, only Vista and 7
Edit: Well, it seems like the only time this happens reproducibly is when it's run by the installer, I believe there's other times it occurs, but I might just be crazy. The launching code is a bit complex to post because we handle various command line launch parameters and it launches a signin form before actually launching the main app etc.
Has anyone had to deal with this scenario before and worked it out?
Try checking your main application form "Form Border" property.
If it's ToolWindow (Fixed or Sizable), try changing it to FixedDialog for example.
This solved the problem in my case.
The usual reason for this is that your main application window doesn't have the window styles that let Windows know it's a main application window (rather than a tool window or a dialog box). So Windows is having to guess based on how the app was started, etc.
Use Spy++ to complare the window styles (especially extended styles) if your window to that of some other window that doesn't have this problem. Are you missing the WS_EX_APPWINDOW style? Are any other styles/extended styles different from other top level windows?
G.So's answer made me find the solution for my problem, wich was caused by the fact that i had my form sizable from launch, but set to borderless in the load void.
If anyone is interested in how i managed to keep the switch to borderless and have it pop up as it should in the taskbar without any dirty hacks.. here it is..
Make a new event from the form on the form's "Shown" event, and put your line of code for switching to borderless in here. Problem solved :)
private void Form1_Shown(object sender, EventArgs e)
{
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
}
and for the lazy ones ;) >>>>
this.Shown += new EventHandler(Form1_Shown);
Thanks again G.So for clearing up what could cause this in the first place.
I stuggled with this issue as well, and found like a previous commenter said, you cannot have anything in the form's Load() event that changes that FormBorderStyle property. Move anything that changes it to the Shown() event.
Well, one solution is to use a hack like this. That's really not what it's for.
Usually the decision of whether a window will be in the taskbar or not is based on the border styles it uses. The article I linked to provides a bit more detail. The article's comment about the window having an owner or not is quite possible highly relevant to your issue, since the window might somehow be getting a different owner when launched by the installer.
That article is in VB but it's all based around API calls so the info it provides is pretty language independent.
Never see this happen in XP, only Vista and 7
Maybe it's a bug in Vista...?
What happens if you call SetForegroundWindow() (or equivalent in .Net)?
Edit
I did of course mean "BringWindowToTop()".
Or do both.
We had this same problem and fixed it by setting the form property showintaskbar property to true.
Weird that all windows os's dont run apps in the same way!
In our situation, this was tracked down to the form's text property being changed within the Load event.
After putting this inside a BeginInvoke, this odd behaviour no longer happened.
Hope this helps anyone else.
Example
private void Form_Load(object sender, EventArgs e)
{
...
...
...
// this needs to be inside a BeginInvoke otherwise it messes with the taskbar visibility
this.BeginInvoke(new Action(() =>
{
this.Text = "Something new";
}));
...
...
...
}
We encountered the same issue, also in Windows 8. Sometimes the form was receiving correctly the focus, but say just ~30% of the time.
We tried different solutions, but actually the one that worked was the following:
private void OnFormShown(object sender, EventArgs e)
{
// Tell Windows that the Form is a main application window
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
// Even if true, enforce the fact that we will the application on the taskbar
this.ShowInTaskbar = true;
// Put the window to the front and than back
this.BringToFront();
this.TopMost = true;
this.TopMost = false;
// 'Steal' the focus.
this.Activate();
}
Moreover, we ensure also not to set the title of the form during the Load event.

Resources