DasBoot
DasBoot

Reputation: 707

WPF event for clicking textboxes in C#

How can I raise an event while clicking a textbox? I'm having trouble finding references for events for WPF in C#.

The idea is to have textboxes fire an event when clicked. For example, let's say as soon as I click a textbox, notepad is executed.

 private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
 {
     hello = Process.Start("notepad");   
 }
 private void Click(object sender, MouseButtonEventArgs e)
 {    
     /* if (e.LeftButton == MouseButtonState.Pressed)
     {
         hello = Process.Start(@"notepad");                
     }*/           
 }

Upvotes: 1

Views: 15798

Answers (2)

Roopz
Roopz

Reputation: 21

MouseLeftButtonDown event can be raised when clicking on textbox. This event will not fire by default on textbox. We need to use UIElement.AddHandler().

For e.g:

XAML:

<Textbox X:Name="Name_Textbox" MouseLeftButtonDown="Name_Textbox_MouseLeftButtonDown"/>

In the class Constructor:

TextBox_Name.AddHandler(FrameworkElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler("Name_Textbox_MouseLeftButtonDown"), true);

Add Event in class file:

private void Name_Textbox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)  
{
   // Your logic on textbox click
}

Upvotes: 0

fenix2222
fenix2222

Reputation: 4730

For text events use TextInput event and read entered character from e.Text

private void yourTextBox_TextInput(object sender, TextCompositionEventArgs e)
{  
    if (e.Text == "K")
    {
    }
}

for mouse events use MouseDown/MouseUp

Sometimes MouseDown/MouseUp won't work on TextBox, then use this one:

http://msdn.microsoft.com/en-us/library/system.windows.uielement.previewmouseup.aspx

Upvotes: 3

Related Questions