Change the mouse drag cursor in WPF - c#

I have to disply the number of dragged files count on mouse cursor while dragging document from file system to my form.
I have done the following code, but I can not change the drag cursor. Please let me know the best way to do this
private void tbDisplayFileContents_PreviewDragOver(object sender, DragEventArgs args)
{
if (IsSingleFile(args) != null)
{
tbDisplayFileContents_PreviewDrop(sender, args);
}
else
{
// args.Effects = DragDropEffects.None;
}
Mouse.SetCursor(Cursors.Hand);
Icon ico = new Icon(string.Concat("1365516094_10371.ico"));
tbDisplayFileContents.Cursor = GenerateCursor.CreateCursor(ico, true, new System.Drawing.Color());
args.Handled = true;
}
private void tbDisplayFileContents_PreviewDrop(object sender, DragEventArgs args)
{
args.Handled = true;
string files = string.Empty;
string[] fileName = IsSingleFile(args);
if (fileName == null) return;
isDrag = true;
DoEvents();
for (int i = 0; i < fileName.Length; i++)
{
if (i == 0)
{
files = string.Concat("1] ", fileName[i]);
}
else
{
int j = i + 1;
files = string.Concat(files, Environment.NewLine, j, "] ", fileName[i]);
}
}
lblfileName.Content = files;
}
private string[] IsSingleFile(DragEventArgs args)
{
if (args.Data.GetDataPresent(DataFormats.FileDrop, true))
{
string[] fileNames = args.Data.GetData(DataFormats.FileDrop, true) as string[];
if (fileNames.Length != 0)
{
if (File.Exists(fileNames[0]))
{
// At this point we know there is a single file.
return fileNames;
}
}
}
return null;
}
#endregion
#region -------Events--------
private void btnClear_Click(object sender, RoutedEventArgs e)
{
lblfileName.Content = string.Empty;
}
#endregion
private void tbDisplayFileContents_PreviewDragEnter(object sender, DragEventArgs e)
{
e.Effects = DragDropEffects.None;
}
public static void DoEvents()
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background,
new Action(delegate
{
Icon ico = new Icon(string.Concat("1365516094_10371.ico"));
Mouse.OverrideCursor = GenerateCursor.CreateCursor(ico, true, new System.Drawing.Color());
}));
}
I have used GiveFeedBack event as follows
private void tbDisplayFileContents_GiveFeedback(object sender, GiveFeedbackEventArgs e)
{
if (e.Effects == DragDropEffects.Copy)
{
e.UseDefaultCursors = false;
// Mouse.SetCursor(Cursors.Hand);
Icon ico = new Icon(string.Concat("1365516094_10371.ico"));
//Mouse.Cursor = GenerateCursor.CreateCursor(ico, true, new System.Drawing.Color());
Mouse.SetCursor(GenerateCursor.CreateCursor(ico, true, new System.Drawing.Color()));
}
else
e.UseDefaultCursors = true;
e.Handled = true;
}
It is working for form to form dragging but it is not working for the contents(file) which is dragged from outside form e.g files from Desktop.

I miss the GiveFeedback event in your code, which is used to modify the Mouse cursor while drag and drop operations.

Related

Create a HaarCascade to output percentages instead of outputting a "true" when a threshold is being surpassed

My goal is to use my webcam to capture my face and detect my mood by facial expression. The output should be probabilites like 70 % happy, 10 % sad, ...
My approach: very happy and very sad ( and other states ) faces should be saved in a HaarCascade.
My problems are twofold:
How do I create a HaarCascade to use with HaarObjectDetector for the
HaarObjectDetector object to output percentages instead of
outputting a "true" when a threshold is being surpassed?
How do I create a HaarCascade for HaarCascade? Is it easier to use String path = #"C:\Users\haarcascade-frontalface_alt2.xml"; HaarCascade cascade1 = HaarCascade.FromXml(path); with opencv-xml or generate it using HaarCascade m = new HaarCascade(20,20,HaarCascadeStages);? What would HaarCascadeStages be?
Have others already solved this issue and offer sourcecode for c#?
My current code:
public partial class Form1 : Form
{
private bool DeviceExist = false;
private FilterInfoCollection videoDevices;
private VideoCaptureDevice videoSource = null;
Bitmap picture;
HaarObjectDetector detector;
FaceHaarCascade cascade;
public Form1()
{
InitializeComponent();
}
// get the devices name
private void getCamList()
{
try
{
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
comboBox1.Items.Clear();
if (videoDevices.Count == 0)
throw new ApplicationException();
DeviceExist = true;
foreach (FilterInfo device in videoDevices)
{
comboBox1.Items.Add(device.Name);
}
comboBox1.SelectedIndex = 0; //make dafault to first cam
}
catch (ApplicationException)
{
DeviceExist = false;
comboBox1.Items.Add("No capture device on your system");
}
}
//toggle start and stop button
private void start_Click(object sender, EventArgs e)
{
}
//eventhandler if new frame is ready
private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
picture = (Bitmap)eventArgs.Frame.Clone();
//Rectangle[] objects = detector.ProcessFrame(picture);
//if (objects.Length > 0)
//{
// RectanglesMarker marker = new RectanglesMarker(objects, Color.Fuchsia);
// pictureBox1.Image = marker.Apply(picture);
//}
pictureBox1.Image = picture;
}
//close the device safely
private void CloseVideoSource()
{
if (!(videoSource == null))
if (videoSource.IsRunning)
{
videoSource.SignalToStop();
videoSource = null;
}
}
//get total received frame at 1 second tick
private void timer1_Tick(object sender, EventArgs e)
{
label2.Text = "Device running... " + videoSource.FramesReceived.ToString() + " FPS";
}
//prevent sudden close while device is running
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
CloseVideoSource();
}
private void Form1_Load(object sender, EventArgs e)
{
getCamList();
cascade = new FaceHaarCascade();
detector = new HaarObjectDetector(cascade, 30);
detector.SearchMode = ObjectDetectorSearchMode.Average;
detector.ScalingFactor = 1.5f;
detector.ScalingMode = ObjectDetectorScalingMode.GreaterToSmaller;
detector.UseParallelProcessing = false;
detector.Suppression = 2;
}
private void rfsh_Click_1(object sender, EventArgs e)
{
}
private void start_Click_1(object sender, EventArgs e)
{
if (start.Text == "Start")
{
if (DeviceExist)
{
videoSource = new VideoCaptureDevice(videoDevices[comboBox1.SelectedIndex].MonikerString);
videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
CloseVideoSource();
videoSource.DesiredFrameSize = new Size(640, 480);
//videoSource.DesiredFrameRate = 10;
videoSource.Start();
label2.Text = "Device running...";
start.Text = "Stop";
timer1.Enabled = true;
}
else
{
label2.Text = "Error: No Device selected.";
}
}
else
{
if (videoSource.IsRunning)
{
timer1.Enabled = false;
CloseVideoSource();
label2.Text = "Device stopped.";
start.Text = "Start";
}
}
}
}

Audio playing stopped when i resize a WaveForm to form size

I have a problem with my audio application. I'm using nAudio library.
So when I play a sound without using "SamplesPerPixel" method on my waveViewer control, everything works perfectly, but when I want assign a value to this method. The Sound, when I play it starts from unexpected time and finish about 4sec. later.
Here is my code:
namespace AudioMixer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int bytesPerSample;
int samples;
int samplespixel;
private NAudio.Wave.WaveStream pcm = null;
private NAudio.Wave.BlockAlignReductionStream stream = null;
private NAudio.Wave.DirectSoundOut output = null;
private void openFileToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Audio File (*.wav;*.mp3)|*.wav;*.mp3;";
if (dialog.ShowDialog() != DialogResult.OK) return;
DisposeWave();
if (dialog.FileName.EndsWith(".mp3"))
{
pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(dialog.FileName));
stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
}
else if (dialog.FileName.EndsWith(".wav"))
{
pcm = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(dialog.FileName));
stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
}
output = new NAudio.Wave.DirectSoundOut();
output.Init(stream);
output.Stop();
waveViewer1.WaveStream = stream;
bytesPerSample = (pcm.WaveFormat.BitsPerSample / 8) * pcm.WaveFormat.Channels;
samples = (int)(pcm.Length / bytesPerSample);
samplespixel = samples / this.Width;
waveViewer1.SamplesPerPixel = samplespixel;
opened_file_name.Text = dialog.FileName;
play_button.Visible = true;
play_button.Enabled = true;
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
waveViewer1.SamplesPerPixel = samplespixel;
}
private void Form1_Load(object sender, EventArgs e)
{
opened_file_name.Text = "Audio file not opened, choose one from Your computer";
play_button.Visible = false;
}
private void play_button_Click(object sender, EventArgs e)
{
if (output != null)
{
if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
{
output.Pause();
}
else if (output.PlaybackState == NAudio.Wave.PlaybackState.Paused)
{
output.Play();
}
else if (output.PlaybackState == NAudio.Wave.PlaybackState.Stopped)
{
output.Play();
}
}
}
private void DisposeWave()
{
if (output != null)
{
if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
{
output.Stop();
output.Dispose();
output = null;
}
}
if (stream != null)
{
stream.Dispose();
stream = null;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DisposeWave();
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
i think this may help you
waveViewer1.SamplesPerPixel = 400;
waveViewer1.StartPosition = 400;

ADD url in textbox to listbox in Windows Form Application c#

Iam new in programming.In windows Form application ,I want user can write a url in textbox and add (with button) in listbox as a favorite list,then user can click in listbox and then go to browser, finaly can save and open the list? whitout Microsoft Sql Database.I Need a source code.
textbox: (Enter your WebSite) : www.google.com
Button:ADD To List Box
Listbox:WWW.Google.com
Button :Save
Button :Open
You have to save the ListBox.Items as plain text file if not wanting to use database. Without binding, this simple problem becomes a little nasty if you start digging into writing it. Here is one of the solution you may need:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int lastIndex = -1;
bool suppressSelectedIndexChanged;
//Click event handler for buttonAdd
private void buttonAdd_Click(object sender, EventArgs e)
{
listBox1.Items.Add(textBox1.Text);
suppressSelectedIndexChanged = true;
listBox1.SelectedIndex = listBox1.Items.Count - 1;
suppressSelectedIndexChanged = false;
}
//Click event handler for buttonRemove
private void buttonRemove_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndices.Count == 0) return;
int k = listBox1.SelectedIndices[0];
suppressSelectedIndexChanged = true;
for (int i = listBox1.SelectedIndices.Count - 1; i >= 0; i--)
listBox1.Items.RemoveAt(listBox1.SelectedIndices[i]);
suppressSelectedIndexChanged = false;
lastIndex = -1;
listBox1.SelectedIndex = k < listBox1.Items.Count ? k : listBox1.Items.Count - 1;
if (listBox1.Items.Count == 0) textBox1.Clear();
}
//Click event handler for buttonSave
private void buttonSave_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "URLs file|*.urls";
save.FileOk += (s, ev) =>
{
using (StreamWriter writer = File.CreateText(save.FileName))
{
foreach (object item in listBox1.Items)
{
writer.WriteLine(item.ToString());
}
}
};
save.ShowDialog();
}
//Click event handler for buttonOpen
private void buttonOpen_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "URLs file|*.urls";
open.FileOk += (s, ev) =>
{
listBox1.Items.Clear();
using (StreamReader reader = File.OpenText(open.FileName))
{
string line = "";
while ((line = reader.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
}
};
open.ShowDialog();
}
//SelectedIndexChanged event handler for listBox1
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (suppressSelectedIndexChanged) return;
if (lastIndex > -1)
{
listBox1.Items[lastIndex] = textBox1.Text;
}
lastIndex = listBox1.SelectedIndex;
if (listBox1.SelectedIndex > -1)
textBox1.Text = listBox1.Items[listBox1.SelectedIndex].ToString();
}
//Click event handler for buttonVisit
private void buttonVisit_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItem == null) return;
System.Diagnostics.Process.Start(listBox1.SelectedItem.ToString());
}
}
Here is the GUI screen shot for you to know which controls are needed:
private void btnAdd_Click(object sender, EventArgs e)
{
string _webstring = #"http://";
string _website = _webstring + textBox1.Text;
listBox1.Items.Add(_website);
using (StreamWriter w = File.AppendText("websites.txt"))
{
WriteLog(_website, w);
}
using (StreamReader r = File.OpenText("websites.txt"))
{
DisposeLog(r);
}
}
private void btnLaunch_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("iexplore.exe", listBox1.SelectedItem.ToString());
}
private void btnSave_Click(object sender, EventArgs e)
{
using (StreamWriter w = File.AppendText("websites.txt"))
{
foreach (string items in listBox1.Items)
{
WriteLog(items, w);
}
}
using (StreamReader r = File.OpenText("websites.txt"))
{
DisposeLog(r);
}
}
public static void WriteLog(string logMessage, TextWriter w)
{
w.WriteLine(logMessage, logMessage);
}
public static void DisposeLog(StreamReader r)
{
string line;
while ((line = r.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
private void btnRetrieve_Click(object sender, EventArgs e)
{
using (TextReader txtRead = File.OpenText("Websites.txt"))
{
string _text = "";
string[] _textArray = null;
while ((_text = txtRead.ReadLine()) != null)
{
_textArray = _text.Split('\t');
listBox1.Items.Add(txtRead.ReadLine());
}
txtRead.Close();
}
}
hope this helps.. thanks

Deleting items from listbox raises exception

I need to be able to delete items from a listbox but when I press the delete function and say yes I want to delete I get this exception: Items collection cannot be modified when the DataSource property is set.
Now I want to know what to do about this.
namespace Flashloader
{
public partial class Form1 : Form
{
private controllerinifile _controllerIniFile;
private toepassinginifile _toepassingIniFile;
// private Toepassinglist _toepassingList;
private StringList _comPorts;
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
button4.Visible = false;
_controllerIniFile = new controllerinifile();
_toepassingIniFile = new toepassinginifile(_controllerIniFile.Controllers);
// _toepassingList = new Toepassinglist(_controllerList).FromIniFile();
_comPorts = new StringList();
_applicationListBox.DataSource = _toepassingIniFile.ToePassingen;
_controllercombobox.DataSource = _controllerIniFile.Controllers;
_applicationListBox.Refresh();
_controllercombobox.Refresh();
Settings settings = _toepassingIniFile.Settings;
textBox3.Text = settings.Port;
textBox4.Text = settings.Baudrate;
}
// File select Button and file directory
private void button2_Click(object sender, EventArgs e)
{
appfile.Filter = "Srec Files (.a20; .a21; .a26; .a44)|*.a20; *.a21; *.a26; *.a44|All files (*.*)|*.*";
{
if (appfile.ShowDialog() == DialogResult.OK)
{
System.IO.StreamReader sr = new
System.IO.StreamReader(appfile.FileName);
sr.Close();
}
}
String filedata = appfile.FileName;
appfile.Title = ("Choose a file");
appfile.InitialDirectory = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Application.ExecutablePath), #"C:\\\\Projects\\flashloader2013\\mainapplication\\");
textBox1.Text = string.Format("{0}", appfile.FileName);
}
// textbox for the bootfile
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
// start button for sending appfiles
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
serialPort1.Open();
if (MessageBox.Show(appfile.FileName + " is selected and ready to be send,Are you sure you want to send the selected file?", "", MessageBoxButtons.YesNo) == DialogResult.No)
{
MessageBox.Show("The selected file will not be send.", "", MessageBoxButtons.OK);
}
else
{
button1.Visible = false;
button4.Visible = true;
}
try
{
using (FileStream inputstream = new FileStream(OpenBoot.FileName, FileMode.Open, FileAccess.Read, FileShare.Read, 32 * 1024 * 1024, FileOptions.SequentialScan))
{
byte[] buffer = new byte[8 * 1024 * 1024];
long bytesRead = 0, streamLength = inputstream.Length;
inputstream.Position = 0;
while (bytesRead < streamLength)
{
long toRead = streamLength - bytesRead;
if (toRead < buffer.Length)
buffer = new byte[(int)toRead];
if (inputstream.Read(buffer, 0, buffer.Length) != buffer.Length)
throw new Exception("File read error");
bytesRead += buffer.Length;
serialPort1.Write(buffer, 0, buffer.Length);
}
}
}
catch
{
MessageBox.Show("No file selected");
}
StringList list = new StringList().FromFile(appfile.FileName);
// Read file and put it in a list that will be sorted.
foreach (String line in list)
{
list.Sort();
serialPort1.Write(line);
}
MessageBox.Show("Bootfile and Applicationfile are send succesfully.");
}
// abort button for sending files
private void button4_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
button4.Visible = false;
button1.Visible = true;
progressBar1.Value = 0;
timer1.Enabled = false;
serialPort1.Close();
}
// backgroundworkers
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
DateTime start = DateTime.Now;
e.Result = "";
for (int i = 0; i < 100; i++)
{
System.Threading.Thread.Sleep(50);
backgroundWorker1.ReportProgress(i, DateTime.Now);
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return;
}
}
TimeSpan duration = DateTime.Now - start;
e.Result = "Duration: " + duration.TotalMilliseconds.ToString() + " ms.";
}
private void backgroundWorker1_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
DateTime time = Convert.ToDateTime(e.UserState);
}
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
MessageBox.Show("The task has been cancelled");
}
else if (e.Error != null)
{
MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString());
}
else
{
MessageBox.Show("The task has been completed. Results: " + e.Result.ToString());
}
}
private void Boot_button_Click(object sender, EventArgs e)
{
OpenBoot.Filter = "Binary Files (.BIN; .md6; .md7)|*.BIN; *.md6; *.md7|All Files (*.*)|*.*";
{
if (OpenBoot.ShowDialog() == DialogResult.OK)
{
System.IO.StreamReader sr = new
System.IO.StreamReader(appfile.FileName);
sr.Close();
}
}
String filedata = OpenBoot.FileName;
OpenBoot.Title = ("Choose a file");
OpenBoot.InitialDirectory = "C:\\Projects\\flashloader2013\\mainapplication\\Bootfiles";
textBox2.Text = string.Format("{0}", OpenBoot.FileName);
}
// Saving the settings to the INI file.
private void SaveSettings()
{
Toepassing toepassing = GetCurrentApplication();
if (toepassing == null)
{
MessageBox.Show("No Application selected");
return;
}
toepassing.Controller = (Controller)_controllercombobox.SelectedItem;
toepassing.Lastfile = textBox1.Text;
// toepassing.TabTip =
_toepassingIniFile.Save();
}
private Controller GetCurrentController()
{
int index = _controllercombobox.SelectedIndex;
if (index < 0)
return null;
return _controllerIniFile.Controllers[index];
}
private Toepassing GetCurrentApplication()
{
int index = _applicationListBox.SelectedIndex;
if (index < 0)
return null;
return _toepassingIniFile.ToePassingen[index];
}
private void typelistbox_SelectedIndexChanged(object sender, EventArgs e)
{
Toepassing toepassing = GetCurrentApplication();
if (toepassing == null)
{
// TODO velden leegmaken
}
else
{
// appfile.InitialDirectory = Path.GetDirectoryName(controller.Lastfile);
appfile.FileName = toepassing.Lastfile;
textBox1.Text = toepassing.Lastfile;
_controllercombobox.SelectedItem = toepassing.Controller;
}
}
private void _controllercombobox_SelectedIndexChanged(object sender, EventArgs e)
{
Controller controller = GetCurrentController();
if (controller == null)
{
// TODO velden leegmaken
}
else
{
textBox2.Text = controller.Bootfile;
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void changeCurrentControllerToolStripMenuItem_Click(object sender, EventArgs e)
{
var controlleredit = new Controlleredit(_controllerIniFile);
controlleredit.Show();
Refresh();
}
private void addControllerToolStripMenuItem_Click(object sender, EventArgs e)
{
var controllersettings = new Newcontroller(_controllerIniFile);
controllersettings.ShowDialog();
_controllercombobox.DataSource = null;
_controllercombobox.DataSource = _controllerIniFile.Controllers;
// Refresh();
// _controllercombobox.Refresh();
}
private void newapplicationBtton_Click(object sender, EventArgs e)
{
var newapplication = new NewApplication(_toepassingIniFile);
newapplication.ShowDialog();
_applicationListBox.DataSource = null;
_applicationListBox.DataSource = _toepassingIniFile.ToePassingen;
}
/////////////////////////////The Error is down here /////////////////////////////
private void button3_Click(object sender, EventArgs e)
{
if (MessageBox.Show("You are about to delete application: "+ Environment.NewLine + _applicationListBox.SelectedItem +Environment.NewLine + " Are you sure you want to delete the application?", "", MessageBoxButtons.YesNo) == DialogResult.No)
{
MessageBox.Show("The application will not be deleted.", "", MessageBoxButtons.OK);
}
else if (this._applicationListBox.SelectedIndex >= 0)
this._applicationListBox.Items.RemoveAt(this._applicationListBox.SelectedIndex);
}
}
}
The error says it quite clearly: you have to remove the item from the underlying datasource, you can't delete it manually. If you want to remove/add items manually, you shouldn't use databinding but build the list by hand.
As exception say you can't delete items directly from ListBox - you have to remove it from underlying DataSource and then rebind control (if it is not bound to BindingSource for example)
private void button3_Click(object sender, EventArgs e)
{
if (MessageBox.Show("You are about to delete application: "+ Environment.NewLine + _applicationListBox.SelectedItem +Environment.NewLine + " Are you sure you want to delete the application?", "", MessageBoxButtons.YesNo) == DialogResult.No)
{
MessageBox.Show("The application will not be deleted.", "", MessageBoxButtons.OK);
}
else if (this._applicationListBox.SelectedIndex >= 0)
{
var item = this.GetCurrentApplication();
_toepassingIniFile.ToePassingen.Remove(item);
_applicationListBox.DataSource = null;
_applicationListBox.DataSource = _toepassingIniFile.ToePassingen;
}
}
Your code is hard to read so I was a bit guessing with classes etc, but it should work.
Try to remove from datasource itself as below:
string myobj = this._applicationListBox.SelectedValue.ToString();
data.Remove(myobj );
_applicationListBox.DataSource = null;
_applicationListBox.DataSource = data;
As others have said. You must have a list that is bound to the listbox. You cannot delete from the listbox directly.
You should delete from the List
private Toepassinglist _toepassingList
That is the datasource for your listbox.
Delete the item you want like so...
this._toepassingList.Items.RemoveAt(this._applicationListBox.SelectedIndex);
You can delete from list:---
ListName.Items.RemoveAt(postion);

Showing virtual keyboard when clicking on a textbox inside WebControl

I have created a virtual keyboard, the keyboard pops up for wpf textbox controls. How can I make the keyboard pops out when clicking on a textbox inside a web page?
the logic for displaying a textbox is given below:
static void TouchScreenKeyboardPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
FrameworkElement host = sender as FrameworkElement;
if (host != null)
{
host.GotFocus += new RoutedEventHandler(OnGotFocus);
host.LostFocus += new RoutedEventHandler(OnLostFocus);
}
}
static void OnGotFocus(object sender, RoutedEventArgs e)
{
Control host = sender as Control;
if (sender == typeof(TextBox))
{
_PreviousTextBoxBackgroundBrush = host.Background;
_PreviousTextBoxBorderBrush = host.BorderBrush;
_PreviousTextBoxBorderThickness = host.BorderThickness;
host.Background = Brushes.Yellow;
host.BorderBrush = Brushes.Red;
host.BorderThickness = new Thickness(4);
}
_CurrentControl = host;
if (_InstanceObject == null)
{
FrameworkElement ct = host;
while (true)
{
if (ct is Window)
{
((Window)ct).LocationChanged += new EventHandler(TouchScreenKeyboard_LocationChanged);
((Window)ct).Activated += new EventHandler(TouchScreenKeyboard_Activated);
((Window)ct).Deactivated += new EventHandler(TouchScreenKeyboard_Deactivated);
break;
}
if(ct.Parent != null)
ct = (FrameworkElement)ct.Parent;
}
_InstanceObject = new TouchScreenKeyboard();
_InstanceObject.AllowsTransparency = true;
_InstanceObject.WindowStyle = WindowStyle.None;
_InstanceObject.ShowInTaskbar = false;
_InstanceObject.ShowInTaskbar = false;
_InstanceObject.Topmost = true;
host.LayoutUpdated += new EventHandler(tb_LayoutUpdated);
}
}
static void TouchScreenKeyboard_Deactivated(object sender, EventArgs e)
{
if (_InstanceObject != null)
{
_InstanceObject.Topmost = false;
}
}
static void TouchScreenKeyboard_Activated(object sender, EventArgs e)
{
if (_InstanceObject != null)
{
_InstanceObject.Topmost = true;
}
}
static void TouchScreenKeyboard_LocationChanged(object sender, EventArgs e)
{
syncchild();
}
static void tb_LayoutUpdated(object sender, EventArgs e)
{
syncchild();
}
static void OnLostFocus(object sender, RoutedEventArgs e)
{
Control host = sender as Control;
host.Background = _PreviousTextBoxBackgroundBrush;
host.BorderBrush = _PreviousTextBoxBorderBrush;
host.BorderThickness = _PreviousTextBoxBorderThickness;
if (_InstanceObject != null)
{
_InstanceObject.Close();
_InstanceObject = null;
}
}
#endregion
}
private static void syncchild()
{
if (_CurrentControl != null && _InstanceObject != null)
{
Point virtualpoint = new Point(0, _CurrentControl.ActualHeight + 3);
Point Actualpoint = _CurrentControl.PointToScreen(virtualpoint);
if (WidthTouchKeyboard + Actualpoint.X > SystemParameters.VirtualScreenWidth)
{
double difference = WidthTouchKeyboard + Actualpoint.X - SystemParameters.VirtualScreenWidth;
_InstanceObject.Left = Actualpoint.X - difference;
}
else if (!(Actualpoint.X > 1))
{
_InstanceObject.Left = 1;
}
else
_InstanceObject.Left = Actualpoint.X;
_InstanceObject.Top = Actualpoint.Y;
_InstanceObject.Show();
}
}
private static void SetKeyInBrowser(string key)
{
var elementName = (((mshtml.HTMLDocument)(dom)).activeElement).id;
if (elementName != null)
{
var existingText = dom.getElementById(elementName).getAttribute("value");
if (existingText == null)
{
existingText = "";
}
//if it's a backspace.
if (isBackspace)
{
existingText = existingText.ToString().Remove(existingText.ToString().Length - 1);
dom.getElementById(elementName).setAttribute("value", existingText.ToString());
}
else if (key.Length != 0)
{
dom.getElementById(elementName).setAttribute("value", existingText.ToString() + key[key.Length - 1]);
}
}
isBackspace = false;
}
You need to use javascript for that. You need to know when that textfield is focused like this:
Check if focus is on a textfield
And then once the focused event is fired on JavaScript you should call your WPF function for showing the keyboard up. Here's useful hints:
How to programmaticaly check if a text input box inside a web page loaded in WPF Browser has focus?

Categories

Resources