Remove icon automatically by dropped file on RichTextBox - c#

I set to true the AllowDrop implemented the DragOver and DragDrop events RichTextBox. On DragDrop event I load the dropped text files' contents on the RTB but it does add the icon of the file in RTB I'd to remove it:
Edit: Here's my code:
void msg_setup_dragDrop()
{
msg_textBox.AllowDrop = true;
msg_textBox.EnableAutoDragDrop = true;
msg_textBox.DragEnter += new DragEventHandler(msg_DragEnter);
msg_textBox.DragDrop += new DragEventHandler(msg_DragDrop);
}
void msg_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
void msg_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[]) e.Data.GetData(DataFormats.FileDrop);
StringBuilder buffer = new StringBuilder();
foreach (string filename in files)
{
try
{
string text = File.ReadAllText(filename);
buffer.Append(text);
}
catch (Exception ex)
{
string errMsg = string.Format("cannot read the file\"{0}\" error: {1}", filename, ex.Message);
MessageBox.Show(errMsg, "Reading file error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
msg_textBox.Text = buffer.ToString();
}

Somewhere you have set msg_textBox.EnableAutoDragDrop = true, either in your designer window or your code. You need to set this to false. You do still need to set AllowDrop = true.
When set to true, the winforms RichTextBox provides standard behaviors for drag-and-drop events, to which your custom handlers are added. If you don't want the standard behavior, you have to completely roll your own handlers. (The standard behavior for a dropped text file is OLE embedding. If you double click on the icon, notepad launches.)

I know this is an old post, but after trying to find a solution for the same problem, I ended up with a work around/solution
The DragDrop Method should be:
private void RTB_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
String[] filename = (String[])e.Data.GetData(DataFormats.FileDrop);
RTB.Text = fileName[0]; //this is where the text is
}
Now, if you have a RTB TextChanged method defined (RTB is rich text box), get the RTB.Text, then set the RTB.Text.
This seems to erase the unwated icons in the RTB
Example:
private void RTB_TextChanged(object sender, EventArgs e)
{
string currentText = RTB.Text.ToString();
RTB.Text = currenText;
}
Note: You have to go to the RTB properties and click on the lightning bolt icon (Events) and point the TextChanged Event to the RTB_TextChanged method you defined. Or just double click on the EventName and it'll create a new method for you to complete the method.

Icon placement; Occurs when the Msg_DragDrop method ends, depending on the e.Effect property.
Add this code to the end of the method=>
E.Effect = DragDropEffects.None;
void msg_DragDrop(object sender, DragEventArgs e)
{
//your code here
e.Effect = DragDropEffects.None;
}

Related

Drag&drop from explorer delete my source file

I work on a Outlook plugin, and i want to drop a file in a listbox (in a outlook region) from explorer. I simply do this:
private void InitializeComponent()
{
this._shareList.DragDrop += new System.Windows.Forms.DragEventHandler(this._shareList_DragDrop);
this._shareList.DragEnter += new System.Windows.Forms.DragEventHandler(this._shareList_DragEnter);
}
private void _shareList_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
{
e.Effect = DragDropEffects.Link;
Cursor.Current = Cursors.Arrow;
}
}
private void _shareList_DragDrop(object sender, DragEventArgs e)
{
string[] tab = (string[])e.Data.GetData(DataFormats.FileDrop, false);
foreach (string filePath in tab)
AttachFile(new FileInfo(filePath));
}
When i drop file from the explorer, the source file is deleted of the disk! Why? Outlook catch the drop event?
So how can i prevent that?
Thanks for your help.
OK I do an error in my code :(
I delete unfortunately the file...
Sorry to bother you.

Refresh ComboBox directory listing in WinForm, onClick for C#

I have a set-up a Windows form that on completion creates a .txt document containing imputed data for the user on one form and then that form can then be opened into a richTextBox on another form using a ComboBox as a selection tool.
The problem I am having is that the ComboBox does not refresh the directory listings where the .txt documents are saved after a new .txt has been created and so the user has to restart the program before it shows up in the ComboBox listing, wondering how to solve this. Possibly force the ComboBox to refresh the listings onClick of a button?
Form with ComboBox selection method on:
public Default()
{
InitializeComponent();
string[] files = Directory.GetFiles(#"C:\Modules");
foreach (string file in files)
ModuleSelectorComboBox.Items.Add(Path.GetFileNameWithoutExtension(file));
}
private void moduleToolStripMenuItem_Click(object sender, EventArgs e)
{
NewModule newmodule = new NewModule();
newmodule.Show();
}
private void ModuleSelectorComboBox_SelectedValueChanged(object sender, EventArgs e)
{
richTextBox1.Clear(); //Clears previous Modules Text
string fileName = (string)ModuleSelectorComboBox.SelectedItem;
string filePath = Path.Combine(#"C:\Modules\", fileName + ".txt");
if (File.Exists(filePath))
richTextBox1.AppendText(File.ReadAllText(filePath));
else
MessageBox.Show("There's been a problem. Please restart the program. \nError 1", "Error 1", //error 1 is file deleted while the program is running
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
}
To add I want to avoid the using of the Dialog save/open file method and is why I am using the ComboBox to do this.
Thanks in advance.
The form to create new .txt document (I don't see this as essentially needed I have just added it for reference):
private void button5_Click(object sender, EventArgs e)
{
RichTextBox newbox = new RichTextBox();
{
String Saved_Module = Path.Combine("C:\\Modules", txtModuleName.Text + ".txt");
newbox.AppendText(txtModuleName.Text + "\n" + ModuleDueDate.Text + "\n" + txtModuleInfo.Text + "\n" + txtModuleLO.Text);
newbox.SaveFile(Saved_Module, RichTextBoxStreamType.PlainText);
Directory.CreateDirectory(Path.Combine(#"C:\Modules", txtModuleName.Text));
this.Close();
}
}
First of all, encapsulate the logic of the combobox population in a method.
public Default()
{
InitializeComponent();
LoadComboBox();
}
void LoadComboBox()
{
ModuleSelectorComboBox.Items.Clear();
string[] files = Directory.GetFiles(#"C:\Modules");
foreach (string file in files)
ModuleSelectorComboBox.Items.Add(Path.GetFileNameWithoutExtension(file));
}
I suggest to open the form as a dialog form using ShowDialog method
and set the DialogResult to DialogResult.OK in the button5_Click method.
private void button5_Click(object sender, EventArgs e)
{
RichTextBox newbox = new RichTextBox();
String Saved_Module = Path.Combine("C:\\Modules", txtModuleName.Text + ".txt");
newbox.AppendText(txtModuleName.Text + "\n" + ModuleDueDate.Text + "\n" + txtModuleInfo.Text + "\n" + txtModuleLO.Text);
newbox.SaveFile(Saved_Module, RichTextBoxStreamType.PlainText);
Directory.CreateDirectory(Path.Combine(#"C:\Modules", txtModuleName.Text));
this.DialogResult = DialogResult.OK;
this.Close();
}
And then, based on the DialogResult load or do not load the combobox's items in the moduleToolStripMenuItem_Click method.
private void moduleToolStripMenuItem_Click(object sender, EventArgs e)
{
NewModule newmodule = new NewModule();
newmodule.ShowDialog();
if (result == DialogResult.OK)
{
LoadComboBox();
}
}
Update:
If you don't want to use a Dialog, you can subscribe to an FormClosing event and update the combobox in a handler to the event.
private void moduleToolStripMenuItem_Click(object sender, EventArgs e)
{
NewModule newmodule = new NewModule();
newmodule.FormClosing += F_FormClosing
newmodule.Show();
}
private void F_FormClosing(object sender, FormClosingEventArgs e)
{
LoadComboBox();
}
I suggest breaking out LoadComboBox as Valentin suggests, but using a FileSystemWatcher instantiated and disposed with the form to monitor the Modules directory and call LoadComboBox on any create/delete.

Drag and Drop forbidden on panel even though AllowDrop is set to true [duplicate]

This question already has an answer here:
File drag and drop not working on listbox
(1 answer)
Closed 7 years ago.
I have a panel on my form on which I have allowed drag and drop. I have written the code to DragEnter and DragDrop events and they were working fine last time I checked. But now when I drag a file over my panel I get the forbidden cursor and the events are no longer triggered. I have looked in my entire project to see if I am disabling AllowDrop somewhere, but I don't.
Here are my events together with the functions they are performing:
this.pnlNoPostbagFolder.AllowDrop = true;
this.pnlNoPostbagFolder.DragDrop += new System.Windows.Forms.DragEventHandler(this.pnlNoPostbagFolder_DragDrop);
this.pnlNoPostbagFolder.DragEnter += new System.Windows.Forms.DragEventHandler(this.pnlNoPostbagFolder_DragEnter);
private void pnlNoPostbagFolder_DragDrop(object sender, DragEventArgs e)
{
FileListDragDrop(sender, e);
}
private void pnlNoPostbagFolder_DragEnter(object sender, DragEventArgs e)
{
FileListDragEnter(sender, e);
}
private void FileListDragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
private void FileListDragDrop(object sender, DragEventArgs e)
{
string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
for (int i = 0; i < s.Length; i++)
{
if (Path.GetExtension(s[i]).Equals(".csv", StringComparison.InvariantCultureIgnoreCase) || Path.GetExtension(s[i]).Equals(".sql", StringComparison.InvariantCultureIgnoreCase))
{
string source = s[i];
string destination = Common.Conf.PostbagFolderLocation + "\\" + Path.GetFileName(s[i]);
if (File.Exists(destination))
{
DialogResult dr = MsgBox.Show(string.Format("A file named '{0}' already exists in the Postbag folder. Overwrite?", Path.GetFileName(s[i])), "File Exists", MsgBox.Buttons.YesNo, MsgBox.Icon.Question);
if (dr == DialogResult.Yes)
{
File.Copy(source, destination, true);
RefreshPostbagFolder();
}
}
File.Copy(source, destination, true);
}
else
MsgBox.Show("File extension not supported", "Add File", MsgBox.Buttons.OK, MsgBox.Icon.Error);
}
}
All of your code seems OK and I don't have any issue with your code in my machine, It seems a UAC issue:
Q: Why Doesn’t Drag-and-Drop work when my Application is Running Elevated?
UAC elevation does not allow drag and drop

Multiple Textbox in a window WPF C#

Iam creating this project which uses on screen keyboard. The problem is I have several textboxes in my window. The question is, when I selected the textbox and start using the on screen keyboard, the text should be displayed on the textbox that I selected.
there will be a possibility that not all the textbox are being used depending on the user's preference.
Here's my sample code when I click the button
private void button_numeric_1_Click(object sender, RoutedEventArgs e)
{
if (txtThousand.Focus())
{
txtThousand.Text += "1";
// txtThousand.Focus();
txtThousand.SelectionStart = txtThousand.Text.Length;
}
else if (txtFivehundred.Focus())
{
txtFivehundred.Text += "1";
txtFivehundred.Focus();
txtFivehundred.SelectionStart = txtThousand.Text.Length;
}
}
My problem now is how can I determine which text box is active.
When I used this code:
private void StartKeyBoardProcess(TextBox tb)
{
try
{
if (tb != null)
{
MessageBox.Show("Pumasok!");
tb.Focus();
}
}
catch (Exception ex)
{
MessageBox.Show("Error");
}
}
private void txtThousand_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
TextBox tb = sender as TextBox;
StartKeyBoardProcess(tb);
}
Nothing happens.
When I Click my button, It only input text in the First Textbox. When I click the other textbox, It continue inputting in the first text box.
Can anyone tell me how to work this out? I'm so new with WPF.
Something like this is the simple solution. You call your method with the textbox you clicked on etc. and start the process and force focus to the texbox you touched.
private void StartKeyBoardProcess(Textbox tb) {
try {
if (tb != null) {
Process.Start("osk.exe", "/C");
tb.Focus();
}
}
catch (Exception ex) {
Messagebox.Show("Error: StartKeyBoardProcess: "+ex);
}
}
private void TextBox_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Textbox tb = sender as Textbox;
StartKeyBoardProcess(tb);
}
Something like this :)
I use PreviewMouseLeftButtonDown event:
private void txtThousand_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
TextBox tb = sender as TextBox;
StartKeyBoardProcess(tb);
}

Get the path of a file dragged into a Windows Forms form

I am developing an application which requires the user to drag a file from Windows Explorer into the application window (Windows Forms form). Is there a way to read the file name, path and other properties of the file in C#?
You can catch the DragDrop event and get the files from there. Something like:
void Form_DragDrop(object sender, DragEventArgs e)
{
string[] fileList = (string[])e.Data.GetData(DataFormats.FileDrop, false);
//more processing
}
you Should Use Two Events
1) DragDrop
2) DragEnter
Also enable "AllowDrop" Property of Panel/form to true.
private void form_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void form_DragDrop(object sender, DragEventArgs e)
{
string[] filePaths= (string[])e.Data.GetData(DataFormats.FileDrop, false);
}

Categories

Resources