can not make it work, whatever I tried so far.
I want to make a Remote Camera Commander application (WPF/C#) in Visual Studio 2015 that consists of a number buttons that, when clicked, do a web request to a network camera. I am not a programmer, so I am starting from scratch.
Have searched the internet for many days now and tested many examples, but when inserting a piece of example code into my code, always new issues arise.
I have made an example that hopefully explains my issues:
MainWindow.xaml:
<Window x:Class="RCC_1v1.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:RCC_1v1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button x:Name="button" Content="GetCameraType_Button" Click="GetType" HorizontalAlignment="Left" Margin="44,108,0,0" VerticalAlignment="Top" Width="168" Height="86"/>
<RichTextBox x:Name="response" HorizontalAlignment="Left" Height="78" VerticalAlignment="Top" Width="169" Margin="246,112,0,0" TextChanged="response_TextChanged">
<FlowDocument>
<Paragraph>
<Run Text ="How to get the response from webclient into this textbox, instead of in the messagebox??"/>
</Paragraph>
</FlowDocument>
</RichTextBox>
</Grid>
MainWindow.xaml.cs:
using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
namespace RCC_1v1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private void GetType(object sender, RoutedEventArgs e)
{
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("stackO", "12345");
wc.DownloadStringAsync(new Uri("http://eremote-cam1.eu.ngrok.io/axis-cgi/param.cgi?action=list&group=root.Brand"));
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
}
private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
MessageBox.Show(e.Result.ToString());
}
private void response_TextChanged(object sender, TextChangedEventArgs e)
{
}
}
}
You can run it yourself with the temp. the account that is embedded. Not sure if I should use TextBox or any other object like listview or.
The expected responses are text-string and single numbers.
Any tip, direction or help is appreciated.
Just followed some of your suggestions, code is now:
enter code hereusing System;
using System.Net;
using System.Windows;
namespace RCC_1v2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private void GetType(object sender, RoutedEventArgs e)
{
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("stackO", "54321");
wc.DownloadStringAsync(new Uri("http://eremote-cam1.eu.ngrok.io/axis-cgi/param.cgi?action=list&group=root.Brand.ProdFullName"));
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
}
private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
this.Dispatcher.BeginInvoke(new Action(() => {
String run_text = e.Result.ToString();
Run1.Text = run_text.Substring(24, 13);
}));
}
}
}
enter image description here
Give the name "Run1" to the Run contained in your XAML using x:Name attribute.
Replace your code:
MessageBox.Show(e.Result.ToString());
with this one:
this.Dispatcher.BeginInvoke(new Action(() => {
this.Run1.Text = e.Result.ToString();
}));
The event DownloadStringCompleted runs in a background thread, so if you want to update the UI you must use the Dispatcher property of the Window class.
Ok I just found out about the idea of posting an answer. With help of the posters I created the next example/solution:
using System;
using System.Net;
using System.Windows;
namespace RCC_1v2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private void GetType(object sender, RoutedEventArgs e)
{
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("xxx", "xxx");
wc.DownloadStringAsync(new Uri("http://eremote-cam1.eu.ngrok.io/axis-cgi/param.cgi?action=list&group=root.Brand.ProdFullName"));
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
}
private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
this.Dispatcher.BeginInvoke(new Action(() => {
String run_text = e.Result.ToString();
Run1.Text = run_text.Substring(24, 13);
}));
}
}
}
Mainwindow.xaml:
<Window x:Class="RCC_1v2.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:RCC_1v2"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button x:Name="button" Content="GetCameraType_Button" Click="GetType" HorizontalAlignment="Left" Margin="44,108,0,0" VerticalAlignment="Top" Width="140" Height="86"/>
<TextBox x:Name="Run1" HorizontalAlignment="Left" Height="78" VerticalAlignment="Top" Width="285" Margin="206,113,0,0" >
</TextBox>
</Grid>
</Window>
As you can see I now have the response in the texbox (and not a RichTextBox)
nb. I was not allowed to post a picture :-(
enter image description here
Thanks!
Related
I created a new WPF app in Visual Studio and I placed a button using the drag and drop editor but I can't access the button in my .cs file using
MainButton.Content = "Set output to red";
but I get an error
System.NullReferenceException: 'Object reference not set to an instance of an object.'
MainButton was null while running the application.
The drag and drop editor generated this xaml file
<Window x:Class="WpfApp1.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:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Border HorizontalAlignment="Center" VerticalAlignment="Center" BorderBrush="Black" BorderThickness="3">
<TextBlock x:Name="Output" Background="Transparent" TextAlignment="Center" TextWrapping="Wrap" Text="Output" Height="88" Width="264"/>
</Border>
<RadioButton x:Name="Option1" Content="Red Pill" HorizontalAlignment="Left" Margin="135,75,0,0" VerticalAlignment="Top" Checked="RadioButton_Checked" IsChecked="True"/>
<RadioButton x:Name="Option2" Content="Blue Pill" HorizontalAlignment="Left" Margin="536,72,0,0" VerticalAlignment="Top" Checked="RadioButton_Checked_1"/>
<Button x:Name="MainButton" Content="Set output to red" HorizontalAlignment="Left" Margin="279,100,0,0" VerticalAlignment="Top" Width="213" Height="41" Click="MainButton_Click"/>
</Grid>
</Window>
Here's the .cs file
using System.Windows;
using System.Windows.Media;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void MainButton_Click(object sender, RoutedEventArgs e)
{
if ((bool)Option1.IsChecked)
{
Output.Background = Brushes.Crimson;
}
else
{
Option2.IsChecked = true;
Output.Background = Brushes.DodgerBlue;
}
}
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
MainButton.Content = "Set output to red";
}
private void RadioButton_Checked_1(object sender, RoutedEventArgs e)
{
MainButton.Content = "Set output to blue";
}
}
}
I can access other things in the UI just fine like radio buttons and text blocks but not the button. Why could this be happening?
During the initialization phase, some variables are going to be null since it hasn't been reached in the call order. RadioButton_Checked is called through event before the button is constructed since it contains the Checked property.
A quick and easy fix is as follows: Check for null in your event calls.
private void RadioButton_Checked (object sender, RoutedEventArgs e)
{
if(MainButton != null)
MainButton.Content = "Set output to red";
}
private void RadioButton_Checked_1 (object sender, RoutedEventArgs e)
{
if (MainButton != null)
MainButton.Content = "Set output to blue";
}
Of course, there are better ways to handle this. You could set checked on a separate event, Initialized, which will handle it much cleaner.
I need help from someone who work in C#. I'm trying to achieve WPF application that open internet explorer on URL that i supplement him as a parameter. So in perfect world i would like run something like this:
\\path\window.exe X x Y "URL" "Title"
Where X,Y is windows height and width, URL and Title is a title of that window. My knowledge of C# is nonexistent so after extensive use of google i manage to get this XAML:
<Window x:Class="WPFWebControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="My Web Browser" WindowState="Normal" Loaded="Window_Loaded" WindowStyle="ThreeDBorderWindow" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Height="Auto" Width="Auto">
<Grid>
<WebBrowser Height="Auto" HorizontalAlignment="Left" Margin="0,28,0,0" Name="MyWebBrowser" VerticalAlignment="Top" Width="Auto" LoadCompleted="MyWebBrowser_LoadCompleted" />
<TextBox Height="23" Margin="40,5,0,0" Name="MyTextBox" VerticalAlignment="Top" HorizontalAlignment="Left" Width="708" />
<Button Content="Go" Margin="10,5,0,476" Name="MyGo" ToolTip="Go" Click="MyGo_Click" RenderTransformOrigin="-0.76,0.565" HorizontalAlignment="Left" Width="25" />
</Grid>
</Window>
and this C# code:
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 WPFWebControl
{ /// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
try
{
MyWebBrowser.Source = new Uri("http://www.google.com");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void MyGo_Click(object sender, RoutedEventArgs e)
{
try
{
MyWebBrowser.Source = new Uri("http://" + MyTextBox.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void MyWebBrowser_LoadCompleted(object sender, NavigationEventArgs e)
{}
}
}
Now i need some advice how can i set window size, url and title via parameters so i can get rid of that address textbox and button.
You could open a new window and set a WebBrowser as its Content, e.g.:
WebBrowser browser = new WebBrowser();
Window win = new Window();
win.Content = browser;
win.Height = 100;
win.Width = 100;
win.Show();
win.Title = "title...";
browser.Navigate("http://google.com");
If you want your application to be able to accept command line arguments, you could remove the StartupUri attribute from your App.xaml and override the OnStartup method of your App.xaml.cs:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
try
{
double width = Convert.ToDouble(e.Args[0]);
double height = Convert.ToDouble(e.Args[1]);
string title = e.Args[2];
string url = e.Args[3];
WebBrowser browser = new WebBrowser();
Window win = new Window();
win.Content = browser;
win.Height = height;
win.Width = width;
win.Show();
win.Title = title;
browser.Navigate(new Uri(url, UriKind.Absolute));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Usage:
WpfApplication1.exe 100 100 "title..." "http://google.com"
You should be able to use
string[] args = Environment.GetCommandLineArgs();
Or, change teh startup uri in App.xaml (remove it) and instead create your own startup like
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
//Manually create and show your window, passing the arguments
}
}
etc
In a WPF application, I have a webbrowser called WebBrowser1. This refers to an HTML page which contains a TextArea to which users can input text.
<html>
<body>
<textarea class="myStudentInput" id="myStudentInput1">
Text to be copied
</textarea>
</body>
</html>
I wish to get this text and potentially also set this text.
I have tried something similar to the javascript way of writing it:
document.getElementById("myStudentOutput1").innerHTML;
such as
HtmlElement textArea = webBrowser1.Document.All["myStudentInput1"];
dynamic textArea = WebBrowser1.Document.GetElementsByID("myStudentInput1").InnerText;
but it doesn't work.
The following solution in Visual Studio 2015 WPF Application works for me.
First, add a reference to the Microsoft HTML COM Library. This is on the COM tab, when you do an "Add Reference" in your project.
Then add the code:
<Window x:Class="WpfApplication3.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:WpfApplication3"
mc:Ignorable="d"
Title="MainWindow" Height="600" Width="800">
<Grid>
<WebBrowser x:Name="WebBrowser1" HorizontalAlignment="Left" Height="480" Margin="10,10,0,0" VerticalAlignment="Top" Width="770" Source="E:\Others\Dropbox\Programming\Questions.html"/>
<Button x:Name="mySetQuestionButton" Content="Set Question" HorizontalAlignment="Left" Margin="200,520,0,0" VerticalAlignment="Top" Width="75" Click="mySetQuestion"/>
<Button x:Name="myGetAnswerButton" Content="Get Answer" HorizontalAlignment="Left" Margin="350,520,0,0" VerticalAlignment="Top" Width="75" Click="myGetAnswer"/>
<TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="600,520,0,0" TextWrapping="Wrap" Text="Hello2" VerticalAlignment="Top"/>
</Grid>
</Window>
and
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 WpfApplication3
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void mySetQuestion(object sender, EventArgs e)
{
mshtml.HTMLDocument document = (mshtml.HTMLDocument)WebBrowser1.Document;
mshtml.IHTMLElement textArea = document.getElementById("myQuestion1");
textArea.innerHTML = "What is 1+1?";
}
private void myGetAnswer(object sender, EventArgs e)
{
mshtml.HTMLDocument document = (mshtml.HTMLDocument)WebBrowser1.Document;
mshtml.IHTMLElement textArea = document.getElementById("myStudentInput1");
textBlock.Text = textArea.innerHTML;
}
}
}
but it doesn't work.
I have no idea what that could possibly mean. All you can get is a code snippet that does work:
public partial class Form1 : Form {
private WebBrowser webBrowser1;
private Button button1;
public Form1() {
button1 = new Button { Text = "Test" };
button1.Click += button1_Click;
this.Controls.Add(button1);
webBrowser1 = new WebBrowser { Dock = DockStyle.Fill };
webBrowser1.DocumentText = #"<html><body><textarea class=""myStudentInput"" id=""myStudentInput1"">Text to be copied</textarea></body></html>";
this.Controls.Add(webBrowser1);
}
private void button1_Click(object sender, EventArgs e) {
var elem = webBrowser1.Document.GetElementById("myStudentInput1");
MessageBox.Show(elem.InnerText);
}
}
Which produces:
At first I want to say that i searched on internet and I didn't found anything. I would like to make a dynamic song list, that when user adds a song, new object will be added with name and lenght and when he selects this song he would get a path to the selected song. Here is code to understand better:
XAML:
<Window x:Class="ListBox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox x:Name="SongList" HorizontalAlignment="Left" Height="278" Margin="10,10,0,0" VerticalAlignment="Top" Width="248"/>
<TextBlock HorizontalAlignment="Left" Margin="287,124,0,0" TextWrapping="Wrap" Text="Path" VerticalAlignment="Top" Width="194" Height="22"/>
<Label Content="Song Path" HorizontalAlignment="Left" Margin="287,98,0,0" VerticalAlignment="Top" Width="194"/>
<Button Content="Add Song" HorizontalAlignment="Left" Margin="10,293,0,0" VerticalAlignment="Top" Width="132" Click="Button_Click"/>
</Grid>
and code:
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
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 ListBox
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openfile = new OpenFileDialog();
openfile.DefaultExt = ".mp3";
openfile.Filter = "mp3 | *.mp3";
Nullable<bool> result = openfile.ShowDialog();
if (result == true)
{
String file = openfile.FileName;
FileInfo fileinfo = new FileInfo(file);
SongList.Items.Add(fileinfo.Name);
}
}
}
}
so where the "Path" text box is I would like to get current selected song path. Is it possible to make with ItemBox or I need to make array that will save all paths?
I think you should use for your songs, because you're writing a WPF application, an ObservableCollection of your song objects, in order to have a proper ListBox with your updated objects.
Then, you have to create a proper Song class with its own properties, like the SongName or the SongPath. In this class, you will implement the INotifyPropertyChanged interface
and, for each property, you will raise an appropriate OnPropertyChanged event.
With this implementation, once you load a song and add it to the songs list, your ListBox will show the updated collection accordingly.
Further info about the ObservableCollection here.
If you want to have a look at a code sample, in this answer I written an example of developing an ObservableCollection.
at first you might want to have a look at MVVM programming. The concept is not that easy to understand, even harder to apply but once you got it you will be able to create good UI in no-time and it's especially perfect for what you are trying to do.
Now to your problem. FileInfo.Name only stores the file name not the path, so if you don't store the path separately, you won't be able to get it back from just the file name.
KillaKem's solution seems pretty good, however I wouldn't recommend using the Tag property for this. Just create a Collections::Generic::List (please, don't use arrays) class member to store the paths and then use the selectedIndexChange Event to update the PathSearchBox.
using MVVM you could just link the ListBox to a Dictionary which stores both, path and filename and just display the Filename, feel free to research MVVM a bit yourself.
Regards,
Xaser
You could try something along the lines of this,
XAML:
<Window x:Class="ListBox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox x:Name="SongList" HorizontalAlignment="Left" Height="278" Margin="10,10,0,0" VerticalAlignment="Top" Width="248"/>
<TextBlock HorizontalAlignment="Left" Margin="287,124,0,0" TextWrapping="Wrap" Text="Path" VerticalAlignment="Top" Width="194" Height="22"/>
<Label Name ="pathLabel" Content="Song Path" HorizontalAlignment="Left" Margin="287,98,0,0" VerticalAlignment="Top" Width="194"/>
<Button Content="Add Song" HorizontalAlignment="Left" Margin="10,293,0,0" VerticalAlignment="Top" Width="132" Click="Button_Click"/>
</Grid>
Back Code:
namespace ListBox
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openfile = new OpenFileDialog();
openfile.DefaultExt = ".mp3";
openfile.Filter = "mp3 | *.mp3";
Nullable<bool> result = openfile.ShowDialog();
if (result == true)
{
String file = openfile.FileName;
FileInfo fileinfo = new FileInfo(file);
SongList.Items.Add(fileinfo.Name);
var pathList = SongList.Tag as List<string>;
pathList.Add(fileinfo.DirectoryName);
SongList.Tag = pathList;
}
}
private void Selection_Changed(object sender, EventArgs e)
{
var myListBox = sender as ListBox;
var myPathList = myListBox.Tag as List<string>;
var filePath = myPathList[myListBox.SelectedIndex];
pathLabel.Content = filePath;
}
}
}
Haven't tested the code but it should be working or close to working.
These is a SelectionChanged event in the listbox you can use. But i would recommend using bi
I have a System.Windows.Controls.TextBox which I would like to behave as follows: When you click it, it is determined dynamically if the TextBox gets focus or not. Here's a toy application which contains a failed attempt at accomplishing this:
<!-- MainWindow.xaml -->
<Window x:Class="Focus.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Label Name="myLabel" Grid.Row="0" Background="Red"></Label>
<TextBox Name="myTextbox" Grid.Row="1" Background="Green"></TextBox>
</Grid>
</Window>
// MainWindow.xaml.cs
using System;
using System.Windows;
using System.Windows.Input;
namespace Focus
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
myTextbox.PreviewGotKeyboardFocus += myTextbox_GotKeyboardFocus;
}
private static readonly Random myRandom = new Random();
private void myTextbox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
int randomInt = myRandom.Next(0, 2); // 0 or 1
myLabel.Content = randomInt;
if(randomInt==0)
{
// PREVENT FOCUS - INSERT CODE HERE. (The line below is a failed attempt.)
FocusManager.SetFocusedElement(this, myLabel);
}
}
}
}
The following code seems to do the trick:
// PREVENT FOCUS - INSERT CODE HERE.
myLabel.Focusable = true;
myLabel.Focus();
myLabel.Focusable = false;
I also changed this line of code:
myTextbox.PreviewGotKeyboardFocus += myTextbox_GotKeyboardFocus;
into this:
myTextbox.GotFocus += myTextbox_GotKeyboardFocus;
I hope you know that you hooked up to the keyboard focus (TAB key).
void textBox1_GotFocus(object sender, System.EventArgs e)
{
if (!this.checkBox1.Checked)
this.checkBox1.Focus();
else
this.textBox1.Focus();
}