Check if window is active or not WPF - c#

I want to subscribe to the Activated and Deactivated events of the class Application but I can't seem to get it right.
I must be doing something wrong cause It's not working I searched around some and found this http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/ and it just seems way too complicated for such an easy task.
I've been looking around in msdn and I eventually tried this http://msdn.microsoft.com/en-us/library/ms366768.aspx but still not working...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace derp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Width = 250;
this.Height = 250;
this.Title = "derp";
Application app = new Application();
app.Activated += Active;
app.Activated += new EventHandler(Active);
}
void Active(object sender, EventArgs args)
{
//Do stuff
}
void Passive(object sender, EventArgs args)
{
//Do stuff
}
}
}

I think the issue here is that you are creating a new Application() and not referencing the actual current one running.
To get the currently running application try using Application.Current instead. [MSDN Ref]
Try instead:
Application app = Application.Current;

Related

How can I access a class passed to a WPF Window?

I'm passing a class to a WPF Window, and binding properties of the class to fields in the WPF Window. I have that working fine, but I want to edit a property of the class, show the changes in the WPF Window, and then return the class back to the application that called the WPF Window.
Here is the code to display the WPF Window. When I try to access newproduct from the RewriteTitle method I cannot.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Inventory_Controller
{
/// <summary>
/// Interaction logic for TitleWindow.xaml
/// </summary>
public partial class TitleWindow : Window
{
public TitleWindow(Product newproduct)
{
this.DataContext = newproduct; //This didn't help
InitializeComponent();
}
private void RewriteTitle(object sender, TextChangedEventArgs e)
{
// Here I want to access newproduct
}
}
}
The easy way to do it is using the private field. You should create a private readonly field to set the value.
public TitleWindow(Product newproduct)
{
this.DataContext = newproduct;
_product = newproduct;
InitializeComponent();
}
private readonly Product _product;
And then you can find the _product in RewriteTitle
private void RewriteTitle(object sender, TextChangedEventArgs e)
{
// Here I want to access newproduct
// Use _product = xx Or _product.Foo = xx;
}

Is Main() required in a WPF application? [duplicate]

This question already has answers here:
No Main() in WPF?
(7 answers)
Closed 4 years ago.
I'm totally new to .NET and I'm trying to get to know C# by running the codes I encounter in the books I follow..
I'm building a simple WPF app with a button, which should print out the hypoteneuse.
My question is; In the bellow code example from the book, there is these two namespaces (Syncfusion and NamespaceDemo). Do I have to include them both? What is a better way to use these code? Secondly, When creating a new WPF file and a button for the application, it automatically generates this piece of code:
public MainWindow()
{
InitializeComponent();
}
I know that the MainWindow() is for the design that will include the button. How does it differs from the Main() function in a simple C# console application?
I would appreciate a clear explaination about my confusion with how this different things has to be structured properly. Do I need a Main()?
This is the code from book:
using static System.Math;
namespace Syncfusion
{
public class Calc
{
public static double Pythagorean(double a, double b)
{ double cSquared = Pow(a, 2) + Pow(b, 2);
return Sqrt(cSquared); }
}
}
using Syncfusion;
using System;
using Crypto = System.Security.Cryptography;
namespace NamespaceDemo
{
class Program
{
static void Main()
{
double hypotenuse = Calc.Pythagorean(2, 3);
Console.WriteLine("Hypotenuse: " + hypotenuse);
Crypto.AesManaged aes = new Crypto.AesManaged();
Console.ReadKey();
}
}
}
This is my implementation, which unfortunately doesn't work.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static System.Math;
namespace Syncfusion
{
public class Calc
{
public static double Pythagorean(double a, double b)
{
double cSquared = Pow(a, 2) + Pow(b, 3);
return Sqrt(cSquared);
}
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
void Button_Click(object sender, RoutedEventArgs e)
{
double hypotenuse = Calc.Pythagorean(2, 4);
MessageBox.Show("Hypotenuse: " + hypotenuse);
}
}
}
All C# programs require a static Main methods as an entry point. MainWindow is a class, not an entry point.

How to use the Debug API in Visual Studio Extension?

I have seen a lot about the related issues, but still feel very puzzled
I now mainly encountered the problem is unable to obtain the current state of the debugging process, such as when to encounter breakpoints.
I have seen a lot of problems that can be used IDebugEventCallback2 to solve the problem, but I was a novice, no specific examples difficult to understand
I have never written this related code, MSDN can be found on the information is also very few examples, if there are some information or examples I would be very grateful....QAQ
English is not my mother tongue, there may be some grammatical mistakes and i feel Sorry for it.
this answer is base on the Visual Studio Package template in C#
File structure is as follows, different project name settings may be different but similar, I have made changes to the selected two documents (MyControl.xaml, VSPackageHW2Package.cs)
FileStruct
1.Define the variable
public static VSPackageHW2Package package;
readonly IVsDebugger _debugger;
readonly DTE _dte;
readonly Debugger2 _dteDebugger;
readonly uint _debuggerEventsCookie;
2.pass value from VSPackageHW2Package.cs to MyControl.xaml(the only place to change VSPackageHW2Package.cs)
public VSPackageHW2Package()
{
Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString()));
MyControl.package = this;
}
3.Implement interface in MyControl.xaml
IVsDebuggerEvents
4.in Constructor
public MyControl()
{
InitializeComponent();
var packageServiceProvider = (IServiceProvider)package;
_debugger = packageServiceProvider.GetService(typeof(SVsShellDebugger)) as IVsDebugger;
_dte = packageServiceProvider.GetService(typeof(SDTE)) as DTE;
if (_debugger.AdviseDebuggerEvents(this, out _debuggerEventsCookie) != VSConstants.S_OK)
{
MessageBox.Show("DebugManager setup failed");
}
else
{
MessageBox.Show("ok");
}
}
Complete MyControl.xaml file:
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Company.VSPackageHW2
{
/// <summary>
/// Interaction logic for MyControl.xaml
/// </summary>
public partial class MyControl : UserControl,IVsDebuggerEvents
{
public static VSPackageHW2Package package;
readonly IVsDebugger _debugger;
readonly DTE _dte;
readonly Debugger2 _dteDebugger;
readonly uint _debuggerEventsCookie;
public MyControl()
{
InitializeComponent();
var packageServiceProvider = (IServiceProvider)package;
_debugger = packageServiceProvider.GetService(typeof(SVsShellDebugger)) as IVsDebugger;
_dte = packageServiceProvider.GetService(typeof(SDTE)) as DTE;
if (_debugger.AdviseDebuggerEvents(this, out _debuggerEventsCookie) != VSConstants.S_OK)
{
MessageBox.Show("DebugManager setup failed");
}
else
{
MessageBox.Show("ok");
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions")]
private void button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(string.Format(System.Globalization.CultureInfo.CurrentUICulture, "We are inside {0}.button1_Click()", this.ToString()),
"lzyToolWindow");
}
public int OnModeChange(DBGMODE dbgmodeNew)
{
MessageBox.Show("debug mode change");
throw new NotImplementedException();
}
}
}

How do I detect Ctrl + S in a Window in C#? My EventArgs don't have `e.Modifiers`

This is my first C# (and first Windows) application. I'd like to respond to a multi-key command, but can't figure out how. Examples on the web use e.Modifiers, e.Control, and override bool ProcessCmdKey, none of which appear options in my IDE. My main class is a System.Windows.Window, so is that the problem? I keep reading about Forms--am I utilizing this?
Here's my class header info.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Configuration;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.WindowsAPICodePack.Dialogs;
//using System.Windows.Forms.
using Winforms = System.Windows.Forms;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Runtime.Serialization.Formatters.Binary;
namespace ContractCutter
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
...
And here's where I try to do things. I also only have the Key class, not Keys.
void CutContractKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.LeftCtrl)
stuff;
}
You can use this:
private void CutContractKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.S && Keyboard.Modifiers == ModifierKeys.Control)
{
MessageBox.Show("CTRL + S");
}
}

How to connect datagrid item to another class

Im new here and a relative beginner with programming in C#. I have a problem with my little programm im trying to put together. it should have three windows (it´s in german but it´s easy to understand). In the first one it should have 4 cars with price, power and model in a datagrid i named DGrid. When you click on the button below the second window pops up and there you can choose what type of insurance you want and if you´re going to pay for it every year, or every half-year,ect... and when you click the button below the third window pops up and there is the Sum you have to pay depending on your car model (which you chose in the first window) and the insurance you picked in the second window. Anyway i did the first 2 windows and it´s working properly but the problem i have is that i don´t know how to connect the car i chose in the first window(class) with the third window (where it makes the calculations).
If i write Autos x= (Autos)DGrid.SelectedItem; in the third window, it says it doesnt recognize DGrid name (which is initialized in the first one).
So the question is: How to get the third window to use the selected item from the first one in order to make the calculations?
Here is the code - first window;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Versicherungsrechner
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
Autos a1 = new Autos("Ferrari", 220, 50000);
Autos a2 = new Autos("Lamborghini", 320, 150000);
Autos a3 = new Autos("Maseratti", 520, 250000);
Autos a4 = new Autos("BMW", 250, 55000);
InitializeComponent();
Autos[] auto = new Autos[] { a1, a2, a3, a4 };
DGrid.ItemsSource = auto;
}
public void OnClick(object sender, RoutedEventArgs e)
{
Details d = new Details();
d.Owner = this;
d.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
d.ShowDialog();
}
}
}
Second Window:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Versicherungsrechner
{
/// <summary>
/// Interaction logic for Details.xaml
/// </summary>
public partial class Details : Window
{
public Details()
{
InitializeComponent();
}
public void AnzeigenClick(object sender, RoutedEventArgs e)
{
Ausgabe a = new Ausgabe();
a.Owner = this;
a.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
a.ShowDialog();
}
}
}
And the third:
namespace Versicherungsrechner
{
/// <summary>
/// Interaction logic for Ausgabe.xaml
/// </summary>
public partial class Ausgabe : Window
{
public Ausgabe()
{
InitializeComponent();
}
}
}
And the Car class:
namespace Versicherungsrechner
{
public class Autos
{
public string modell { get; set; }
public double leistung { get; set; }
public double preis { get; set; }
public Autos(string modell, double leistung, double preis)
{
this.modell = modell;
this.leistung = leistung;
this.preis = preis;
}
}
}
If you change this class...
public partial class Ausgabe : Window
{
public Ausgabe()
{
InitializeComponent();
}
}
...to this...
public partial class Ausgabe : Window
{
public Autos SelectedAuto {get;set}
public Ausgabe()
{
InitializeComponent();
}
}
You can then change this code...
public void AnzeigenClick(object sender, RoutedEventArgs e)
{
Ausgabe a = new Ausgabe();
a.Owner = this;
a.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
a.ShowDialog();
}
...to this...
public void AnzeigenClick(object sender, RoutedEventArgs e)
{
Ausgabe a = new Ausgabe();
a.SelectedAuto = DGrid.SelectedValue as Autos;
a.Owner = this;
a.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
a.Setup(); // to do
a.ShowDialog();
}
And this will let the Aufgabe class have something to work with. You can repeat this process with the other classes.
obligatory best practices note: This was the sort of approach people used up until about 2006/2007 before data binding and Xaml became popular. In this era, the approach is considered risky because it invites operational risk. But for the moment it answers your question and lets you proceed with your project.

Categories