What I am trying to do:
I want my program to ping a server to see if it is up.
Additionally I want to want the option to tick a checkbox for persistent pinging. That is Ping every 30 seconds (for 9999 times)
If I enter an IP address without the checkbox and press enter, it works.
If I tick the checkbox, after 30 secs, I get a successful ping (assuming the ping was successful)but it never tries a second time.
I think the problem is with the timer inside the for loop.
In easy terms I want:
-If checkbox is ticked
-then every 30 seconds for 9999 times
-run the ping method
-else run it once
I have read a lot about this but tbh, Ive reached the edge of my understanding. Any help/tips will be gratefully received!
Here is my code (the bits I think count)
using System.Net.NetworkInformation;
using System.Timers;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
namespace PingProject
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
textBoxIPaddress1.KeyDown += textBoxIPaddress1_KeyDown;
}
private void textBoxIPaddress1_KeyDown(object sender, KeyEventArgs e)
{
if (Keyboard.IsKeyDown(Key.Enter))
{
if (every30secs1.IsChecked.Equals(true))
{
for (int pingCount = 0; pingCount < 9999; pingCount++)
{
pingAction1(this, new RoutedEventArgs());
timer = new Timer(30000);
timer.Enabled = true;
timer.Start();
timer.Elapsed += Timer_Elapsed;
}
}
else pingAction1(this, new RoutedEventArgs());
}
}
public static Timer timer;
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
timer.Dispose();
}
public void pingAction1(object sender, RoutedEventArgs e)
{
try
{
Ping Ping1 = new Ping();
PingReply pingReply1 = Ping1.Send(textBoxIPaddress1.Text, 1000);
textBoxResponseTime1.Text = (pingReply1.RoundtripTime.ToString() + "ms");
if (pingReply1.Status == IPStatus.Success)
{
successIndicatorRectangle1.Fill = new SolidColorBrush(Color.FromRgb(0, 111, 0));
textBoxError1.Text = ("Successful");
}
else
{
successIndicatorRectangle1.Fill = new SolidColorBrush(Color.FromRgb(222, 0, 0));
textBoxError1.Text = ("Not successful");
}
}
catch
{
textBoxError1.Text = ("Ping operation failed, check IP address or domain name");
successIndicatorRectangle1.Fill = new SolidColorBrush(Color.FromRgb(222, 0, 0));
}
}
private void buttonClear1_Click(object sender, RoutedEventArgs e)
{
successIndicatorRectangle1.Fill = new SolidColorBrush(Color.FromRgb(102, 102, 102));
textBoxError1.Text = (null);
textBoxIPaddress1.Text = (null);
textBoxResponseTime1.Text = (null);
}
}
}
XAML is:
<Window x:Class="PingProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:PingProject"
mc:Ignorable="d"
Title="MainWindow" Height="431" Width="753">
<Grid x:Name="um" Margin="19,35,0,10" HorizontalAlignment="Left" Width="714" RenderTransformOrigin="0.413,0.534">
<Grid.RowDefinitions>
<RowDefinition Height="10*"/>
<RowDefinition Height="117*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0*"/>
<ColumnDefinition Width="19*"/>
<ColumnDefinition Width="296*"/>
<ColumnDefinition Width="65*"/>
<ColumnDefinition Width="260*"/>
<ColumnDefinition Width="74*"/>
</Grid.ColumnDefinitions>
<Rectangle x:Name="successIndicatorRectangle1" Grid.Column="2" Fill="#666666" HorizontalAlignment="Left" Height="45" Margin="0,52,0,0" Grid.Row="1" Stroke="Black" VerticalAlignment="Top" Width="611" Grid.ColumnSpan="3"/>
<Label x:Name="labelPing_Project" Content="Ping Project" HorizontalAlignment="Left" Margin="256,9,0,0" VerticalAlignment="Top" Width="95" Height="35" Grid.Column="2" FontSize="18" Grid.ColumnSpan="2" Grid.RowSpan="2"/>
<TextBox x:Name="textBoxIPaddress1" HorizontalAlignment="Left" Height="23" Margin="10,64,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="150" SelectionOpacity="0" Grid.Column="2" Grid.Row="1" ToolTip="Enter IP address" Cursor="IBeam" IsReadOnlyCaretVisible="True" ForceCursor="True"/>
<TextBox x:Name="textBoxResponseTime1" HorizontalAlignment="Left" Height="23" Margin="216,64,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="55" SelectionOpacity="0" Grid.Column="2" Grid.Row="1" ToolTip="Response Time" RenderTransformOrigin="-1.34,2.652"/>
<TextBox x:Name="textBoxError1" Grid.Column="3" Height="23" Margin="0,64,0,0" Grid.Row="1" TextWrapping="Wrap" Text="Results" VerticalAlignment="Top" Cursor="No" Grid.ColumnSpan="2" HorizontalAlignment="Left" Width="305"/>
<CheckBox x:Name="every30secs1" Content="" Grid.Column="2" HorizontalAlignment="Left" Margin="181,64,0,0" Grid.Row="1" VerticalAlignment="Top" RenderTransformOrigin="0.588,0.812" Width="20" Height="23" ToolTip="Tick this box to ping every 30 secs"/>
<Label x:Name="labelHost1" Content="Host" Grid.Column="2" HorizontalAlignment="Left" Margin="56,26,0,0" Grid.Row="1" VerticalAlignment="Top" Height="26" Width="35"/>
<Label x:Name="label1" Content="" Grid.Column="2" HorizontalAlignment="Left" Margin="150,20,0,0" Grid.Row="1" VerticalAlignment="Top" Height="26" Width="10"/>
<Label x:Name="labelResponse1" Content="Response" Grid.Column="2" HorizontalAlignment="Left" Margin="216,26,0,0" Grid.Row="1" VerticalAlignment="Top" Height="26" Width="61"/>
<Label x:Name="labelNotes1" Content="Notes" Grid.Column="4" HorizontalAlignment="Left" Margin="35,26,0,0" Grid.Row="1" VerticalAlignment="Top" Height="26" Width="41"/>
<Button x:Name="buttonClear1" Content="Clear" Grid.Column="5" HorizontalAlignment="Left" Margin="0,52,0,0" Grid.Row="1" VerticalAlignment="Top" Width="40" Height="45" IsCancel="True" Click="buttonClear1_Click"/>
</Grid>
</Window>
This is my first post here, so If I have messed it up, sorry, please be kind and guide me =0)
You have to change a bit what you are doing. IMHO the flow should be like this:
On every30secs1.CheckedChanged handler you have to check. When the checkbox is going to Checked = true, then you have to activate the timer with this code:
timer.Start();
Whenever the Checked property change to false then:
timer.Stop();
Then, on the handler of your Timer_Elapsed you have to do this:
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
timer.Stop();
for(int i = 0; i < 9999 ; i++)
{
pingAction1(this, new RoutedEventArgs());
counter ++;
Thread.Sleep(30000);
}
}
catch (Exception ex)
{
//Do something
}
finally
{
timer.Start();
}
}
Related
I'm working on an Windows Application where you can block and allow programs. I have a problem on how to call the comboboxitem. inc is an item inside combobox 1 and all is an item inside combobox 2. I want to create a condition where if both comboboxitem are selected run this. How do i do that ? Thank you
private void addSubmitBtn_Click(object sender, RoutedEventArgs e)
{
foreach (string path in pathT.Text.Split(';'))
if (File.Exists(path))
{
if ( inc.SelectedIndex > -1 && all.SelectedIndex > -1)
{
FWRule(path, NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN, (blo.Checked) ? NET_FW_ACTION_.NET_FW_ACTION_BLOCK : NET_FW_ACTION_.NET_FW_ACTION_ALLOW, ((Control)sender).Tag.ToString());
}
if (outg.Checked || all.Checked)
{
FWRule(path, NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT, (blo.Checked) ? NET_FW_ACTION_.NET_FW_ACTION_BLOCK : NET_FW_ACTION_.NET_FW_ACTION_ALLOW, ((Control)sender).Tag.ToString());
}
}
((System.Windows.Controls.Panel)this.Parent).Children.Remove(this);
}
private void FWRule(string path, NET_FW_RULE_DIRECTION_ d, NET_FW_ACTION_ fwaction, string action)
{
try
{
INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FWRule"));
firewallRule.Action = fwaction;
firewallRule.Enabled = true;
firewallRule.InterfaceTypes = "All";
firewallRule.ApplicationName = path;
firewallRule.Name = "PRST: " + System.IO.Path.GetFileName(path);
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallRule.Direction = d;
if (action == "1") firewallPolicy.Rules.Add(firewallRule);
else
{
((System.Windows.Controls.Panel)this.Parent).Children.Remove(this);
}
}
catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message, "ERROR"); }
}
private void addCancelBtn_Click(object sender, RoutedEventArgs e)
{
((System.Windows.Controls.Panel)this.Parent).Children.Remove(this);
}
private void addBackBtn_Click(object sender, RoutedEventArgs e)
{
((System.Windows.Controls.Panel)this.Parent).Children.Remove(this);
}
private void pathT_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void blo_CheckedChanged(object sender, EventArgs e)
{
}
private void al_CheckedChanged(object sender, EventArgs e)
{
}
private void Button_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();
fd.Filter = "Executable|*.exe";
fd.Multiselect = true;
if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
pathT.Text = String.Join(";", fd.FileNames);
}
}
}
}
This is the XAML part
<UserControl x:Class="WpfDeepTest.Views.policyAddFunc"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:md="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:local="clr-namespace:WpfDeepTest.Views"
mc:Ignorable="d"
d:DesignHeight="700" d:DesignWidth="960">
<Grid Background="{DynamicResource MaterialDesignPaper}">
<Grid.RowDefinitions>
<RowDefinition Height=".5*"/>
<RowDefinition Height="3*"/>
<RowDefinition Height="1*"/>
<RowDefinition Height=".5*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="20 0 0 0">
<Button Name="addBackBtn" Style="{DynamicResource MaterialDesignFloatingActionButton}" Width="40" Height="40" Click="addBackBtn_Click">
<md:PackIcon Kind="ChevronLeft" Height="30" Width="30"/>
</Button>
</Grid>
<md:Card Grid.Row="1" Margin="15 10" Padding="100 0" Height="400">
<StackPanel VerticalAlignment="Center">
<Grid Margin="0 0 0 0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="1.5*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="Application Path: " VerticalAlignment="Center" FontSize="25" Foreground="#616161" Padding="10 0 0 0"/>
<TextBox Name="pathT" Grid.Column="1" Background="#F5F5F5" VerticalContentAlignment="Center" FontSize="20" md:HintAssist.Hint="Ex: InboundPolicy#1" Padding="5 0" Margin="0,0,57.2,10.2" TextChanged="TextBox_TextChanged_1"/>
<Button Content="..." Grid.Column="1" HorizontalAlignment="Left" Margin="372,-1,0,0" VerticalAlignment="Top" Width="47" Height="36" Click="Button_Click"/>
</Grid>
<Grid Margin="0 30 0 0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="1.5*"/>
</Grid.ColumnDefinitions>
</Grid>
<Grid Margin="0 30 0 0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="280*"/>
<ColumnDefinition Width="138*"/>
<ColumnDefinition Width="13*"/>
<ColumnDefinition Width="31*"/>
<ColumnDefinition Width="66*"/>
<ColumnDefinition Width="171*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="Directions: " VerticalAlignment="Center" FontSize="25" Foreground="#616161" Padding="10 0 0 0" Margin="0,-25,0,25"/>
<ComboBox x:Name="Combobox1" Grid.Column="1" Background="#F5F5F5" VerticalContentAlignment="Center" FontSize="20" Padding="5 0" Margin="0,-31,0.2,39" Grid.ColumnSpan="5">
<ComboBoxItem Name="all" Content="All" HorizontalAlignment="Left" Width="417.6"/>
<ComboBoxItem Name="inc" IsSelected="True" >OutBound</ComboBoxItem>
<ComboBoxItem Name="outg">InBound</ComboBoxItem>
</ComboBox>
</Grid>
<Grid Margin="0 30 0 0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="280*"/>
<ColumnDefinition Width="108*"/>
<ColumnDefinition Width="61*"/>
<ColumnDefinition Width="163*"/>
<ColumnDefinition Width="87*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="Action: " VerticalAlignment="Center" FontSize="25" Foreground="#616161" Padding="10 0 0 0" Grid.ColumnSpan="2" Margin="2,-34,106,32.4"/>
<ComboBox x:Name="Combobox2" SelectedItem="" Grid.Column="1" Background="#F5F5F5" VerticalContentAlignment="Center" FontSize="20" Padding="5 0" Margin="2,-30,-1.8,36.4" Grid.ColumnSpan="4">
<ComboBoxItem Name="blo" IsSelected="True">Block</ComboBoxItem>
<ComboBoxItem Name="al">Allow</ComboBoxItem>
</ComboBox>
</Grid>
</StackPanel>
</md:Card>
<StackPanel Orientation="Horizontal" Grid.Row="2" HorizontalAlignment="Center">
<Button Name="addSubmitBtn" Style="{DynamicResource MaterialDesignRaisedButton}" VerticalAlignment="Top" Margin="10 20" Content="Submit" Width="150" Height="35" TabIndex="1" Click="addSubmitBtn_Click"/>
<Button Name="addCancelBtn" Style="{DynamicResource MaterialDesignRaisedLightButton}" VerticalAlignment="Top" Margin="10 20" Content="Cancel" Width="150" Height="35" Click="addCancelBtn_Click"/>
</StackPanel>
</Grid>
Here is a screenshot of the program
enter image description here
UPDATE
combobox items can be selected but not checked right? you should check if they are selected only. unless you build your own control that has a combobox of checkboxe items that can be checked
i think I found your problem, on your if condition, the situation can never happen because inc and all are part of <ComboBox x:Name="Combobox1", and in your code you are saying if ( inc.SelectedIndex > -1 && all.SelectedIndex > -1) those two can not be selected in the same time ;)
This for example should work because it has an OR operator if (outg.Checked || all.Checked), thous only one of those should be selected.
ignore below part, is a solution thinking that you were using Win Forms
you can use the selectedIndexChanged
like this for example:
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
this.getValues(this.comboBox2, this.comboBox3);
}
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
this.getValues(this.comboBox2, this.comboBox3);
}
public void compareValues(String value1, String value2)
{
if(value1.Equals("inc") && value2.Equals("all"))
{
this.runThis();
}
}
public void runThis()
{
//do your thing here :)
this.label1.Text = "run this!!!";
}
public void getValues(ComboBox cmb2, ComboBox cmb3)
{
String cmb1Value = "";
String cmb2Value = "";
try{
cmb1Value = this.comboBox2.SelectedItem.ToString();
}catch (Exception exception){
//not both set
}
try
{
cmb2Value = this.comboBox3.SelectedItem.ToString();
}catch (Exception exception){
//not both set
}
this.compareValues(cmb1Value, cmb2Value);
}
example of above code, running:
I'm trying something new. I've got a few grids, and when I try to grab a grid i want to move its parent around my top grid. At the moment I get a System.NullReferenceException on m_startOffset = new Vector(translate.X, translate.Y); in the Grid_MouseDown method. Does someone know how i should tackle this problem?
UI:
<Grid x:Name="GridHost">
<Grid x:Name="GRLogin" Margin="1401,292,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Width="501" d:IsHidden="True" Focusable="True">
<Grid Height="30" VerticalAlignment="Top" Background="#FF1585B5" Margin="0" MouseLeftButtonUp="Grid_MouseUp" MouseLeftButtonDown="Grid_MouseDown" MouseMove="Grid_MouseMove" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button x:Name="GRLoginClose" Content="X" Background="{x:Null}" Foreground="White" FontWeight="Bold" OpacityMask="Black" Margin="470,0,0,0" Width="30" Height="30" Click="Close"/>
<Button Content="-" Background="{x:Null}" Foreground="White" FontWeight="Bold" OpacityMask="Black" Margin="0,0,30,0" Width="30" Height="30" HorizontalAlignment="Right"/>
<Label Content="Login" HorizontalAlignment="Center" Margin="0" FontWeight="Bold"/>
</Grid>
<Grid HorizontalAlignment="Left" Height="250" Margin="0,30,0,0" VerticalAlignment="Top" Width="500" Background="#FF262626">
<PasswordBox HorizontalAlignment="Center" Margin="206,130,120,94" VerticalAlignment="Center" Width="174"/>
<Label Content="Password" HorizontalAlignment="Center" Margin="122,130,308,94" VerticalAlignment="Center" RenderTransformOrigin="-1.737,0.462" Width="70"/>
<Label Content="Username" HorizontalAlignment="Center" Margin="122,99,308,125" VerticalAlignment="Center" RenderTransformOrigin="0.5,0.5" Width="70"/>
<TextBox HorizontalAlignment="Center" Height="23" Margin="206,99,120,125" TextWrapping="Wrap" VerticalAlignment="Center" Width="174" RenderTransformOrigin="0.467,-0.346"/>
<Button Content="Login" HorizontalAlignment="Left" VerticalAlignment="Top" Width="258" Margin="122,180,0,0" Height="40" Background="#FF1585B5" Foreground="White" FontWeight="Bold"/>
</Grid>
</Grid>
Movement code:
private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
{
FrameworkElement element = ((Grid)sender).Parent as Grid;
TranslateTransform translate = element.RenderTransform as TranslateTransform;
m_start = e.GetPosition(GridHost);
m_startOffset = new Vector(translate.X, translate.Y);
element.CaptureMouse();
}
private void Grid_MouseMove(object sender, MouseEventArgs e)
{
FrameworkElement element = ((Grid)sender).Parent as Grid;
TranslateTransform translate = element.RenderTransform as TranslateTransform;
if (element.IsMouseCaptured)
{
Vector offset = Point.Subtract(e.GetPosition(GridHost), m_start);
translate.X = m_startOffset.X + offset.X;
translate.Y = m_startOffset.Y + offset.Y;
}
}
private void Grid_MouseUp(object sender, MouseButtonEventArgs e)
{
FrameworkElement element = ((Grid)sender).Parent as Grid;
element.ReleaseMouseCapture();
}
Declare the parent Grid's RenderTransform in the XAML:
<Grid x:Name="GRLogin" Margin="1401,292,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Width="501" d:IsHidden="True" Focusable="True">
<Grid.RenderTransform>
<TranslateTransform/>
</Grid.RenderTransform>
...
</Grid>
You could also check the RenderTransform for null, in which case you set it: element.RenderTransform = new TranslateTransform();
I have created a window which is a numbered keypad :
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Name="btnTotal" Width="280" Height="60" Grid.ColumnSpan="3" Grid.Row="0" Margin="10,10,10,10" Background="#302F37" Foreground="AntiqueWhite" FontSize="35"></TextBox>
<Button x:Name="btnZzero" Content="0" Width="80" Height="60" Grid.Column="0" Grid.Row="4" Margin="5,5,5,5" Background="#302F37" Foreground="White" Focusable="False" Click="btnZzero_Click"></Button>
<Button x:Name="btnOk" Content="OK" Width="80" Height="60" Grid.Column="1" Grid.Row="4" Margin="5,5,5,5" Click="btnOk_Click" Background="#FF8FC377" Focusable="False"></Button>
<Button x:Name="btnCancel" Content="Cancel" Width="80" Height="60" Grid.Column="2" Grid.Row="4" Margin="5,5,5,5" Click="cancel_Click" BorderBrush="Black" Background="#FFD64D4D" Focusable="False"></Button>
<Button x:Name="btnOne" Content="1" Width="80" Height="60" Grid.Column="0" Grid.Row="3" Margin="14,6,0,6" Focusable="False" Background="#302F37" Foreground="White" HorizontalAlignment="Left" Click="btnOne_Click"></Button>
<Button x:Name="btnTwo" Content="2" Width="80" Height="60" Grid.Column="1" Grid.Row="3" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White" Click="btnTwo_Click"/>
<Button x:Name="btnThree" Content="3" Width="80" Height="60" Grid.Column="2" Grid.Row="3" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White"/>
<Button x:Name="btnFour" Content="4" Width="80" Height="60" Grid.Column="0" Grid.Row="2" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White"></Button>
<Button x:Name="btnFive" Content="5" Width="80" Height="60" Grid.Column="1" Grid.Row="2" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White"></Button>
<Button x:Name="btnSix" Content="6" Width="80" Height="60" Grid.Column="2" Grid.Row="2" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White"></Button>
<Button x:Name="btnSeven" Content="7" Width="80" Height="60" Grid.Column="0" Grid.Row="1" Margin="12,5,9,6" Focusable="False" Background="#302F37" Foreground="White"></Button>
<Button x:Name="btnEight" Content="8" Width="80" Height="60" Grid.Column="1" Grid.Row="1" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White"></Button>
<Button x:Name="btnNine" Content="9" Width="80" Height="60" Grid.Column="2" Grid.Row="1" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White"></Button>
Now, I would like to call this keypad at different times in my application to do different things.
IE I want to use it for a login screen :
<Window x:Class="WpfApplication2.MainLogin2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainLogin2" WindowState="Maximized" Width="1024" Height="768" WindowStyle="None" WindowStartupLocation="CenterScreen">
<Grid Background="#FF260538">
<Grid.RowDefinitions>
<RowDefinition Height="768" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1024" />
</Grid.ColumnDefinitions>
<TextBox Name="userIDTextBox" HorizontalAlignment="Left" Height="47" Margin="402,249,0,0" TextWrapping="Wrap" Text="User ID" VerticalAlignment="Top" Width="213" FontSize="30" PreviewMouseDown="userIDTextBox_PreviewMouseDown" />
<TextBox Name="passcodeTextBox" Height="47" Margin="402,317,0,0" TextWrapping="Wrap" Text="Passcode" VerticalAlignment="Top" Width="213" FontSize="30" HorizontalAlignment="Left" PreviewMouseDown="passcodeTextBox_PreviewMouseDown" />
<Button Content="OK" HorizontalAlignment="Left" Margin="402,386,0,0" VerticalAlignment="Top" Width="213" Height="59" FontSize="30" Click="okButton_Click"/>
<Button Content="CANCEL" HorizontalAlignment="Left" Margin="402,450,0,0" VerticalAlignment="Top" Width="213" Height="59" FontSize="30" Click="cancelButton_Click_1"/>
</Grid>
My problem is how do I pass the result from the keypad back to different text fields after I have clicked ok?
Here is the code behind the keypad window. I only have the number 1 working so far for testing:
namespace WpfApplication2
{
public partial class QuantityKeypad : Window
{
bool btnClicked = false;
string quantityResult = "";
public QuantityKeypad()
{
InitializeComponent();
}
private void cancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btnOk_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btnZzero_Click(object sender, RoutedEventArgs e)
{
}
private void btnOne_Click(object sender, RoutedEventArgs e)
{
if (btnClicked == true)
{
btnTotal.Text = "";
btnClicked = false;
}
quantityResult = quantityResult += "1";
btnTotal.Text = quantityResult;
}
private void btnTwo_Click(object sender, RoutedEventArgs e)
{
}
}
}
And here is the code for the login screen :
namespace WpfApplication2
{
public partial class MainLogin2 : Window
{
public MainLogin2()
{
InitializeComponent();
}
//OK button
private void okButton_Click(object sender, RoutedEventArgs e)
{
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
this.Close();
}
//Cancel button - takes user back to login screen
private void cancelButton_Click_1(object sender, RoutedEventArgs e)
{
this.Close();
}
//Removes text from login textboxes when clicked in
//opens instance of Quantitykeypad when clicking inside textbox
private void userIDTextBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
userIDTextBox.Text = "";
QuantityKeypad loginKeypad = new QuantityKeypad();
loginKeypad.Owner = this;
loginKeypad.ShowDialog();
}
//Removes text from passcode textboxe when clicked in
//opens instance of Quantitykeypad when clicking inside passcode textbox
private void passcodeTextBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
passcodeTextBox.Text = "";
QuantityKeypad loginKeypad = new QuantityKeypad();
loginKeypad.Owner = this;
loginKeypad.ShowDialog();
}
}
}
Terribly sorry if this is simple but I have been struggling for days now.
Thanks
You can make your private field quantityResult a publicly accessible property instead:
public string QuantityResult { get; private set; }
That way, you can read from it:
passcodeTextBox.Text = "";
QuantityKeypad loginKeypad = new QuantityKeypad();
loginKeypad.Owner = this;
loginKeypad.ShowDialog();
passcodeTextBox.Text = loginKeypad.QuantityResult;
I am learning c# and I have been asked to work on a project using WPF, which I don't know much. We are using MUI as well.
I am trying to achieve a pretty basic task. I have two pages called ClientRNG.xamland ServerRNG.xaml. In ClientRNG.xaml I have two buttons and two textfield, when each button is pressed a random number is generated and it appears in a text box. In ServerRNG there are just one button and one textfield, with the same functionality as mentioned above.
So I'll end up with three different random numbers, one in ServerRNG.xaml and two in ClientRNG.
What i want to do is to pass these random numbers to another page called SSL.xaml.
The pages are created in MainWindow.xml:
<mui:ModernWindow.MenuLinkGroups>
<mui:LinkGroup DisplayName="network security">
<mui:LinkGroup.Links>
<mui:Link DisplayName="Home" Source="/Pages/Home.xaml" />
<mui:Link DisplayName="RNG" Source="/Pages/ClientRNG.xaml" />
<mui:Link DisplayName="3DES" Source="/Pages/3des.xaml" />
<mui:Link DisplayName="RSA" Source="/Pages/RSA.xaml" />
<mui:Link DisplayName="SHA-1" Source="/Pages/sha1.xaml" />
<mui:Link DisplayName="PKI Certificates" Source="/Pages/pki.xaml" />
<mui:Link DisplayName="SSL" Source="/Pages/SSL.xaml" />
</mui:LinkGroup.Links>
</mui:LinkGroup>
<mui:LinkGroup DisplayName="settings" GroupName="settings">
<mui:LinkGroup.Links>
<mui:Link DisplayName="software" Source="/Pages/Settings.xaml" />
</mui:LinkGroup.Links>
</mui:LinkGroup>
</mui:ModernWindow.MenuLinkGroups>
<mui:ModernWindow.TitleLinks>
<mui:Link DisplayName="settings" Source="/Pages/Settings.xaml" />
</mui:ModernWindow.TitleLinks>
Code in ClientRNG:
namespace NetworkSecuritySSLTest.Pages
{
/// <summary>
/// Interaction logic for RNG.xaml
/// </summary>
public partial class ClientRNG : UserControl
{
public ClientRNG()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Random r = new Random(1);
int number = r.Next(0, 100);
r1Out.Text = number.ToString();
SharingManager.GlobalValue = number;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Random r = new Random(3);
int number = r.Next(0, 100);
pmsOutC.Text = number.ToString();
}
here is the code I have in ServerRNG:
namespace NetworkSecuritySSLTest.Pages
{
/// <summary>
/// Interaction logic for RNG.xaml
/// </summary>
public partial class ServerRNG : UserControl
{
private SplitPage1 sp;
public ServerRNG()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Random r = new Random(2);
int number = r.Next(0, 100);
r2Out.Text = number.ToString();
SharingManager.GlobalValue = number;
}
}
}
and this is the code behind SSL class
namespace NetworkSecuritySSLTest.Pages
{
/// <summary>
/// Interaction logic for SplitPage1.xaml
/// </summary>
public partial class SplitPage1 : UserControl
{
private int r1FromClient;
public SplitPage1()
{
InitializeComponent();
SharingManager.ValueChanged += UpdateTextBox1;
SharingManager.ValueChanged += UpdateTextBox2;
}
public void UpdateTextBox1(object sender, NumericEventArgs e)
{
r1SSLBox.Text = e.Value.ToString(); // Update textBox
}
public void UpdateTextBox2(object sender, NumericEventArgs e)
{
r2SSLBox.Text = e.Value.ToString(); // Update textBox
}
}
}
here are the xaml:
'SplitPage1'
<UserControl x:Class="NetworkSecuritySSLTest.Pages.SplitPage1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mui="http://firstfloorsoftware.com/ModernUI"
mc:Ignorable="d"
d:DesignWidth="766.507" Height="535">
<Grid Style="{StaticResource ContentRoot}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="6"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ScrollViewer>
<StackPanel>
<TextBlock Text="CLIENT" Style="{StaticResource Heading2}" />
<TextBlock x:Name="hello" Text="Hello Server. This is my Random Number and my Security Capabilities:" FontSize="12" FontStyle="Italic" Margin="0,10,0,0" UseLayoutRounding="False" TextWrapping="Wrap" />
<TextBlock x:Name="helloCont" Text="" FontSize="12" FontStyle="Italic" Margin="0,0,0,0" />
<TextBox x:Name ="r1SSLBox" HorizontalAlignment="Left" Height="57" Margin="10,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.498,0.404"/>
<TextBox x:Name ="r2SSLBox" HorizontalAlignment="Left" Height="57" Margin="10,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.498,0.404"/>
<TextBlock x:Name="VerifyDC" Text="I need to verify your Digital Certificate:" FontSize="12" FontStyle="Italic" Margin="0,10,0,0" />
<TextBlock x:Name="VerifyCont" Text="" FontSize="12" FontStyle="Italic" />
<TextBlock x:Name="MSK" Text="My Master Key is:" FontSize="12" FontStyle="Italic" Margin="0,10,0,0" />
<TextBlock x:Name="MSKCont" Text="" FontSize="12" FontStyle="Italic" />
</StackPanel>
</ScrollViewer>
<GridSplitter Grid.Column="1" />
<ScrollViewer Grid.Column="2 " Margin="{StaticResource SplitRight}">
<StackPanel>
<TextBlock Text="SERVER" Style="{StaticResource Heading2}" />
<TextBlock Text="Content goes here" />
</StackPanel>
</ScrollViewer>
<GridSplitter Grid.ColumnSpan="3" HorizontalAlignment="Left" Margin="0,23,0,0" VerticalAlignment="Top" Width="735"/>
<Button Content="Man-In-The-Middle-Attack" HorizontalAlignment="Left" VerticalAlignment="Top" Width="209" RenderTransformOrigin="0.055,0.397" Height="40" Margin="255,451,0,0" Grid.ColumnSpan="3" />
</Grid>
ClientRNG
<UserControl x:Class="NetworkSecuritySSLTest.Pages.ClientRNG"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mui="http://firstfloorsoftware.com/ModernUI"
mc:Ignorable="d"
d:DesignWidth="766.507" Height="535">
<Viewbox Stretch="None">
<Grid Style="{StaticResource ContentRoot}" Height="301" Margin="0" Width="435">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="0*"/>
</Grid.ColumnDefinitions>
<!-- TODO: set #SelectedSource -->
<mui:ModernTab Layout="Tab" Margin="0,52,0,0">
<mui:ModernTab.Links>
<!-- TODO: set #Source -->
<mui:Link DisplayName="Client" />
<mui:Link DisplayName="Server" Source="/Pages/ServerRNG.xaml" />
</mui:ModernTab.Links>
</mui:ModernTab>
<Button Content="GENERATE R# 1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.055,0.397" Height="26" Margin="10,52,0,0" FontSize="11" Click="Button_Click" />
<TextBox Name ="r1Out" HorizontalAlignment="Left" Height="57" Margin="10,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.498,0.404"/>
<Button Content="GENERATE MS" HorizontalAlignment="Left" VerticalAlignment="Top" Width="119" RenderTransformOrigin="0.055,0.397" Height="26" Margin="306,52,0,0" Click="Button_Click_2" />
<TextBox Name ="msOutC" HorizontalAlignment="Left" Height="57" Margin="306,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="119" RenderTransformOrigin="0.498,0.404"/>
<Button Content="GENERATE PMS" HorizontalAlignment="Left" VerticalAlignment="Top" Width="133" RenderTransformOrigin="0.055,0.397" Height="26" Margin="151,52,0,0" Click="Button_Click_1" />
<TextBox Name ="pmsOutC" HorizontalAlignment="Left" Height="57" Margin="151,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="133" RenderTransformOrigin="0.498,0.404"/>
<Label Content="Random Number Generator" HorizontalAlignment="Left" Height="19" Margin="10,10,0,0" VerticalAlignment="Top" Width="415" FontWeight="Bold"/>
</Grid>
</Viewbox>
and ServerRNG
<UserControl x:Class="NetworkSecuritySSLTest.Pages.ServerRNG"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mui="http://firstfloorsoftware.com/ModernUI"
mc:Ignorable="d"
d:DesignWidth="766.507" Height="535">
<Viewbox Stretch="None">
<Grid Style="{StaticResource ContentRoot}" Height="301" Margin="0" Width="435">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="0*"/>
</Grid.ColumnDefinitions>
<!-- TODO: set #SelectedSource -->
<mui:ModernTab Layout="Tab" Margin="0,52,0,0">
<mui:ModernTab.Links>
<!-- TODO: set #Source -->
<mui:Link DisplayName="Client" Source="/Pages/ClientRNG.xaml" />
<mui:Link DisplayName="Server" />
</mui:ModernTab.Links>
</mui:ModernTab>
<Button Name ="r2but" Content="GENERATE R# 2" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.055,0.397" Height="26" Margin="76,52,0,0" FontSize="11" Click="Button_Click_1" />
<TextBox Name ="r2Out" HorizontalAlignment="Left" Height="57" Margin="76,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.498,0.404"/>
<Button Content="GENERATE MS" HorizontalAlignment="Left" VerticalAlignment="Top" Width="119" RenderTransformOrigin="0.055,0.397" Height="26" Margin="249,52,0,0" />
<TextBox Name ="msOutS" HorizontalAlignment="Left" Height="57" Margin="249,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="119" RenderTransformOrigin="0.498,0.404"/>
<Label Content="Random Number Generator" HorizontalAlignment="Left" Height="19" Margin="10,10,0,0" VerticalAlignment="Top" Width="415" FontWeight="Bold"/>
</Grid>
</Viewbox>
Now I was trying to use the solution posted by Omribitan but i am still struggling
According to what you said in the comment section that SplitPage1 is already shown,
What you are doing in your code is creating a new instance of SplitPage1 and passing it your data
SplitPage1 sp = new SplitPage1(); // This is a new page, not the one currently shown in your application
sp.Setr1SSLBox(number); // it should set the text box in SSL page
So if you want to set the text of the currently displayed SplitPage1, you need to get it's reference. It's hard to say how because I can't see your entire code but this is what I would consider:
Using IoC container to resolve the current instance of SplitPage1.
According to your code seems like there is a third party creating these pages. If that's true, it could pass ServerRNG a reference of the SplitPage1 it's creating which you'll be able to use later, for example :
public partial class ServerRNG : UserControl
{
private SplitPage1 sp;
public ServerRNG(SplitPage1 splitPage) : this()
{
sp = splitPage; // Save a reference to the currently displayed `SplitPage1` page
}
public ServerRNG()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Random r = new Random(2);
int number = r.Next(0, 100);
r2Out.Text = number.ToString();
sp.Setr1SSLBox(number); // Set the correct instance's text
}
}
Create a class which will expose a static property and event that will fire when that property changes:
public class SharingManager
{
// Define a global static event to be fired when the value is changing
public static event EventHandler<NumericEventArgs> ValueChanged;
public static int GlobalValue
{
set
{
// Fire ValueChanged event
if (ValueChanged != null)
ValueChanged(null, new NumericEventArgs(value));
}
}
}
public class NumericEventArgs : EventArgs
{
public NumericEventArgs(int value)
{
Value = value;
}
public int Value { get; set; }
}
Register a handler in SplitPage1
public SplitPage1()
{
InitializeComponent();
SharingManager.ValueChanged += UpdateTextBox;
}
public void UpdateTextBox(object sender, NumericEventArgs e)
{
r1SSLBox.Text = e.Value.ToString(); // Update textBox
}
In Button_Click_1 on ServerNRG, update the value to fire the event
Random r = new Random(2);
int number = r.Next(0, 100);
r2Out.Text = number.ToString();
SharingManager.GlobalValue = number;
Hope this helps
you should work on WPF using the MVVM design pattern.
Its kinda annoying without MVVM framework
I suggest you to use http://caliburnmicro.codeplex.com/
use this tutorial to get started
http://www.mindscapehq.com/blog/index.php/2012/01/12/caliburn-micro-part-1-getting-started/
it also explains how to use the mediator pattern (using caliburn micros event aggerator) to pass values/commands between diffrent windows.
http://www.mindscapehq.com/blog/index.php/2012/2/1/caliburn-micro-part-4-the-event-aggregator/
I have the following DataTemplate:
<DataTemplate x:Key="ToDoListBoxItemTemplate">
<Grid x:Name="item2Expanded" HorizontalAlignment="Left" VerticalAlignment="Top" Width="480" Background="{Binding Converter={StaticResource RowColour}}" MinHeight="81">
<StackPanel HorizontalAlignment="Left" VerticalAlignment="Top" Width="420" Margin="60,0,0,0">
<TextBox x:Name="taskTitle" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding ItemName}" VerticalAlignment="Top" Width="420" Background="{x:Null}" BorderBrush="{x:Null}" CaretBrush="#FF0080FF" SelectionBackground="#FFCFCFCF" Foreground="#FF4E4E4E" BorderThickness="3,3,3,6" FontSize="29.333" Style="{StaticResource listTextBoxTemplate}" InputScope="Text" SelectionForeground="#FF4E4E4E" KeyUp="taskTitle_KeyUp" LostFocus="taskTitle_LostFocus" Tap="taskTitle_Tap" IsReadOnly="True" Margin="0,1,0,0" DoubleTap="taskTitle_DoubleTap"/>
<TextBox x:Name="taskDetail" HorizontalAlignment="Left" TextWrapping="Wrap" Text="Tea is an essential English beverage, it has a nice calming effect, and is often served alongside biscuits." VerticalAlignment="Top" Width="420" Background="{x:Null}" BorderBrush="{x:Null}" CaretBrush="#FF0080FF" SelectionBackground="#FFCFCFCF" Foreground="#FF878787" BorderThickness="3,0,3,6" FontSize="21.333" Style="{StaticResource listTextBoxTemplate}" InputScope="Text" SelectionForeground="#FF878787" Margin="0,-20,0,0" KeyUp="taskDetail_KeyUp" LostFocus="taskDetail_LostFocus" Padding="2,5,2,2" IsHitTestVisible="False"/>
<Grid Height="170" Margin="0,-20,0,0">
<Button x:Name="chooseDateButton" Content="27/06/2013" HorizontalAlignment="Left" Margin="6,13,0,0" VerticalAlignment="Top" BorderBrush="#FF959595" Foreground="#FF959595" Width="157" HorizontalContentAlignment="Left" FontSize="20" Style="{StaticResource selectorButtonTemplate}"/>
<Button x:Name="chooseTimeButton" Content="12:00" HorizontalAlignment="Left" Margin="146,13,0,0" VerticalAlignment="Top" BorderBrush="#FF959595" Foreground="#FF959595" Width="99" HorizontalContentAlignment="Left" FontSize="20" Style="{StaticResource selectorButtonTemplate}"/>
<Button x:Name="setOrClearButton" Content="REMIND ME" HorizontalAlignment="Left" Margin="228,13,0,0" VerticalAlignment="Top" BorderBrush="#FF959595" Foreground="White" Width="180" FontSize="20" Background="#FF959595" Style="{StaticResource greyButtonTemplate}"/>
<Button x:Name="deleteButton" Content="DELETE TASK" HorizontalAlignment="Left" Margin="6,85,0,0" VerticalAlignment="Top" BorderBrush="#FFEE4747" Foreground="White" Width="180" FontSize="20" Background="#FFEE4747" Style="{StaticResource redButtonTemplate}"/>
<Image x:Name="retractButton" Margin="347,107,21,11" Source="/Assets/retract.png" Stretch="Fill" Tap="retractButton_Tap"/>
</Grid>
</StackPanel>
<CheckBox x:Name="checkBox" IsChecked="{Binding IsComplete, Mode=TwoWay}" Content="" HorizontalAlignment="Left" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="{x:Null}" Width="72" BorderThickness="0" Template="{StaticResource checkBoxTemplate}" Checked="checkBox_Checked" Unchecked="checkBox_Unchecked"/>
</Grid>
</DataTemplate>
Where the Grid item2Expanded is placed dynamically in a ListBox (Name="allToDoItemsListBox"). Text is added to each item via bindings.
The image retractButton has Tap="retractButton_Tap", As shown in the code:
private void retractButton_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
if (isItemExpanded == true)
{
// Compacts current item
itemGrid.Height = taskTitle.ActualHeight; // Restores itemGrid height to fit only taskTitle
taskTitle.IsReadOnly = true; // taskTitle becomes only double-tap editable, single tap to expand once more
taskDetail.IsHitTestVisible = false; // Stops overlapping taps
isItemExpanded = false;
}
// Adds the event handler for single tap event
tapTimer.Tick += new EventHandler(tapTimer_Tick);
tapTimer.Start();
}
private void tapTimer_Tick(object sender, EventArgs e)
{
// Stop timer
tapTimer.Tick -= new EventHandler(tapTimer_Tick);
tapTimer.Stop();
// Rest of the single tap function
if (isItemExpanded == false)
{
taskDetail.IsHitTestVisible = true;
taskDetail.IsEnabled = false;
// Expands current item
itemGrid.Height = double.NaN; // Sets itemGrid height to auto
isItemExpanded = true;
// Yeah... don't ask.
// Stops temporary text highlighting/auto jumping to keyboard
taskTitle.IsEnabled = false;
taskTitle.IsEnabled = true;
taskDetail.IsEnabled = true;
}
}
But I cannot access itemGrid, taskTitle, or taskDetail for this specific item. And I have no idea how to pass them to the tapTimer_Tick function.
I have been able to use the Tag="{binding itemID}" on elements, but that still hasn't allowed me to solve this issue.
How do I find the grid item2Expanded that the Tap originated from, and then access elements in the same grid by name?
If I want to access the same element as was clicked, then it's easy:
private void taskTitle_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
TextBox taskTitle = (TextBox)sender;
taskTitle.IsEnabled = false;
}
I've been trying to work out how to use Visual Tree Helper to solve this problem, but I have no idea how to do it.