How do I cut, copy and paste with formatting? - c#

I have a WinForms application with a richTextBox. I would like to be able to cut, copy and paste formatted text in my application. Currently, my code consists of:
Cut all:
richTextBoxPrintCtrl1.Cut();
Cut Selected:
Clipboard.SetText(richTextBoxPrintCtrl1.Text);
richTextBoxPrintCtrl1.Text = "";
Copy all:
richTextBoxPrintCtrl1.Copy();
Copy Selected:
Clipboard.SetDataObject(richTextBoxPrintCtrl1.SelectedText);
Paste:
DataFormats.Format myFormat = DataFormats.GetFormat(DataFormats.Text);
richTextBoxPrintCtrl1.Paste(myFormat);
I would like it so that if I cut/copy text from the richTextBox, it keeps ALL formatting (size, font, colour etc.), and if I paste text to the richTextBox, it also keeps all formatting.
How would this be achieved?
Thanks.

Try this two function:
COPY
private void Copy()
{
Clipboard.SetText(richTextBox1.Rtf, TextDataFormat.Rtf);
}
PASTE
private void Paste()
{
if (Clipboard.ContainsText(TextDataFormat.Rtf))
{
richTextBox1.Rtf = Clipboard.GetText(TextDataFormat.Rtf);
}
}

Related

Store all information about the text of a richtextbox and reconstruct it- c# winforms

Is there a way to store all of the information about the text in a richtextbox (colors, sizes, fonts, etc) and reconstruct it in another richtextbox, which is not in the same form or project?
For example, I have a richtextbox which its text contains multiple fonts and colors, and some lines are centered, and I want to reconstruct it in another richtextbox.
I added that the new richtextbox is not in the same project, so i need to restore the information somewhere (for example, even in a string or a file).
To copy the text and formatting from one richTextBox to another, simply use:
richtextBox2.Rtf = richtextBox1.Rtf;
The Rtf property is simply a string, so you can do with it whatever you can do with strings.
You can do that with the following steps
assume we have two projects
the first is WinFormApp1 and the second is WinFormApp2
Save the RTF of the RichTextBox1 in WinFormApp1 in a text file
In WinFormApp1
const string path = #"D:\RichTextBox\Example.txt";
var rtbInfo = richTextBox1.Rtf;
if (!File.Exists(path))
{
File.Create(path);
TextWriter textWriter = new StreamWriter(path);
textWriter.WriteLine(rtbInfo);
textWriter.Close();
}
else if (File.Exists(path))
{
File.WriteAllText(path, rtbInfo);
}
Read the data from the text file and assigned to RTF of the RichTextBox1 in WinFormApp2
In WinFormApp2
private void Form1_Load(object sender, EventArgs e)
{
const string path = #"D:\RichTextBox\Example.txt";
if (File.Exists(path))
{
richTextBox1.Rtf = System.IO.File.ReadAllText(path);
}
}

How can I output a string that can be copied to the Clipboard?

I am using a MessageBox to output a string that I want to be able to copy the text from and paste elsewhere.
A MessageBox does not allow you to copy the text that it displays, so I need another option that would work.
I'm using:
MessageBox.Show("Test!");
If you just want to let a User select and copy the Text from a TextBox, you could create your own Form with a TextBox inside and then show it, with .Show() or .ShowDialog().
The latter will present a Modal Form, as the Dialog created by MessageBox.Show().
You can also create it on the fly; clicking on a Button, for example:
private void button1_Click(object sender, EventArgs e)
{
ShowMyDialog("Dialog Title", "Test!");
}
private void ShowMyDialog(string title, string text)
{
var form = new Form() {
Text = title,
Size = new Size(250, 80)
};
form.Controls.Add(new TextBox() {
Font = this.Font,
Text = text,
Size = new Size(150, this.Font.Height),
Location = new Point(50, 10)
});
form.ShowDialog();
form.Controls.OfType<TextBox>().First().Dispose();
form.Dispose();
}
If you instead want to put some text in the ClipBoard, you could use ClipBoard.SetText:
Clears the Clipboard and then adds text data in the Text or
UnicodeText format, depending on the operating system.
Clipboard.SetText("My String");
Then you can paste the string (where possible) with Ctrl+V or Shift+Insert or get it back in code with Clipboard.GetText;
string fromClipBoard = Clipboard.GetText();
You can also specify a Text Format using the TextDataFormat enumerator:
Clipboard.SetText([HtmlContent], TextDataFormat.Html);

How can I handle or remove the trailing space of a LinkLabel?

I'm trying to insert links into my RichTextBox. I do not mean setting DetectUrls to true, I want alternate text. What I have so far seems to be working mostly fine.. I'm using much of the code from this solution. But my issue is that there is some trailing whitespace in the LinkLabel that end up cutting off some of the text that follows it.
Here is what I have so far:
private void Form1_Load(object sender, EventArgs e)
{
//My text with a placeholder for the link: %link1%
//NOTE: I can see the leading '>' fine, but the '<' gets hidden by the link label, and it looks like a space between the link text and "Near..."
richTextBox1.Text = "This has a link here:>%link1%<Near the middle.";
LinkLabel link1 = new LinkLabel();
//link1.Margin = new Padding(0); //Doesn't help
//link1.Padding = new Padding(0); //Default is already 0
//What I want to see in my hyperlink
link1.Text = "My_Link_Text";
link1.Font = richTextBox1.Font;
link1.LinkColor = Color.DodgerBlue;
link1.LinkClicked += Link_LinkClicked;
LinkLabel.Link data = new LinkLabel.Link();
//For now, just test with google.com...
data.LinkData = #"http://google.com";
link1.Links.Add(data);
link1.AutoSize = true;
link1.Location = this.richTextBox1.GetPositionFromCharIndex(richTextBox1.Text.IndexOf("%link1%"));
richTextBox1.Controls.Add(link1);
//Replace the placeholder with the text I want to see so that the link gets placed over this text
richTextBox1.Text = richTextBox1.Text.Replace("%link1%", link1.Text);
//Attempt to manually shrink the link by a few pixels (doesn't work)
//NOTE: Turns out this cuts back on the link test, but leave the trailing space :(
//Size s = new Size(link1.Width, link1.Height); //Remember the autosized size (it did the "hard" work)
//link1.AutoSize = false; //Turn off autosize
//link1.Width = s.Width - 5;
//link1.Height = s.Height;
}
The LinkClicked event, just for the curious. Nothing special.
private void Link_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start(e.Link.LinkData.ToString());
}
Here is what I see, for reference (notice the missing '<'):
The reason for using a RichTextBox is that I also plan on adding formatting when I am finished (ability for text to be bold, colored, etc.). I'm basically 2 hours away from scrapping the RichTextBox and drawing everything manually onto a panel and handling click position...

How to replace some text with picture in RichTextBox without clipboard? [duplicate]

Most of the examples I see say to put it on the clipboard and use paste, but that doesn't seem to be very good because it overwrites the clipboard.
I did see one method that manually put the image into the RTF using a pinvoke to convert the image to a wmf. Is this the best way? Is there any more straightforward thing I can do?
The most straightforward way would be to modify the RTF code to insert the picture yourself.
In RTF, a picture is defined like this:
'{' \pict (brdr? & shading? & picttype & pictsize & metafileinfo?) data '}'
A question mark indicates the control word is optional.
"data" is simply the content of the file in hex format. If you want to use binary, use the \bin control word.
For instance:
{\pict\pngblip\picw10449\pich3280\picwgoal5924\pichgoal1860 hex data}
{\pict\pngblip\picw10449\pich3280\picwgoal5924\pichgoal1860\bin binary data}
\pict = starts a picture group,
\pngblip = png picture
\picwX = width of the picture (X is the pixel value)
\pichX = height of the picture
\picwgoalX = desired width of the picture in twips
So, to insert a picture, you just need to open your picture, convert the data to hex, load these data into a string and add the RTF codes around it to define a RTF picture. Now, you have a self contained string with picture data which you can insert in the RTF code of a document. Don't forget the closing "}"
Next, you get the RTF code from your RichTextBox (rtbBox.Rtf), insert the picture at the proper location, and set the code of rtbBox.Rtf
One issue you may run into is that .NET RTB does not have a very good support of the RTF standard.
I have just made a small application* which allows you to quickly test some RTF code inside a RTB and see how it handles it. You can download it here:
RTB tester (http://your-translations.com/toys).
You can paste some RTF content (from Word, for instance) into the left RTF box and click on the "Show RTF codes" to display the RTF codes in the right RTF box, or you can paste RTF code in the right RTB and click on "Apply RTF codes" to see the results on the left hand side.
You can of course edit the codes as you like, which makes it quite convenient for testing whether or not the RichTextBox supports the commands you need, or learn how to use the RTF control words.
You can download a full specification for RTF online.
NB It's just a little thing I slapped together in 5 minutes, so I didn't implement file open or save, drag and drop, or other civilized stuff.
I use the following code to first get the data from clipboard, save it in memory, set the image in clipboard, paste it in Rich Text Box and finally restore the data in Clipboard.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
OpenFileDialog1.Filter = "All files |*.*"
OpenFileDialog1.Multiselect = True
Dim orgdata = Clipboard.GetDataObject
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
For Each fname As String In OpenFileDialog1.FileNames
Dim img As Image = Image.FromFile(fname)
Clipboard.SetImage(img)
RichTextBox1.Paste()
Next
End If
Clipboard.SetDataObject(orgdata)
End Sub
The OpenFileDailog1, RichTextBox1 and Button1 are Open File Dialog, Rich Text Box and button controls respectively.
private void toolStripButton1_Click(object sender, EventArgs e)
{
FileDialog fDialog = new OpenFileDialog();
fDialog.CheckFileExists = true;
fDialog.CheckPathExists = true;
fDialog.RestoreDirectory = true;
fDialog.Title = "Choose file to import";
if (fDialog.ShowDialog() == DialogResult.OK)
{
string lstrFile = fDialog.FileName;
Bitmap myBitmap = new Bitmap(lstrFile);
// Copy the bitmap to the clipboard.
Clipboard.SetDataObject(myBitmap);
DataFormats.Format format = DataFormats.GetFormat(DataFormats.Bitmap);
// After verifying that the data can be pasted, paste
if(top==true && this.rtTop.CanPaste(format))
{
rtTop.Paste(format);
}
if (btmLeft == true && this.rtBottomLeft.CanPaste(format))
{
rtBottomLeft.Paste(format);
}
if (btmCenter == true && this.rtBottomCenter.CanPaste(format))
{
rtBottomCenter.Paste(format);
}
if (btmRight == true && this.rtBottomRight.CanPaste(format))
{
rtBottomRight.Paste(format);
}
}
}
Here is what I do to hack the rich text control:
Insert the required image in wordpad or MS-WORD. Save the file as 'rtf'. Open the rtf file in notepad to see the raw rtf code. Copy the required tags & stuff to the 'rtf' property of your Rich Text Box (append to existing text).
There is some trial and error involved but works.
With C#, I use place holder StringBuilder objects with the necessary rtf code. Then I just append the image path.
This is a workaround for not having to learn the RTF syntax.
My own version that I posted in a new thread, apparently I should have searched and posted it here. Anyway, using the clipboard again, very easy.
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Images |*.bmp;*.jpg;*.png;*.gif;*.ico";
openFileDialog1.Multiselect = false;
openFileDialog1.FileName = "";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
Image img = Image.FromFile(openFileDialog1.FileName);
Clipboard.SetImage(img);
richTextBox1.Paste();
richTextBox1.Focus();
}
else
{
richTextBox1.Focus();
}
}
}
If you were in C++, the way to do it is thru OLE. More specifically, if you search Google for ImageDataObject it will show C++ code how to insert a HBITMAP into the RTF Control. One link is here.
Now, how this translates into .Net code, I don't know. I currently don't have the time to work thru the details.
I was also looking for something for this same task and found this ->
http://sourceforge.net/projects/netrtfwriter/
You can generate any type of RTF text that you would want and then use it however you wish. Very well structured example which will auto sense the image type being used (jpg/jpeg/png etc) and worked for the image files I have been using. If you are in a hurry then this is a great RTF generator!
All I did was make a small pictureBox control in c# and made sure it was hidden behind another object big enough to hide it. Then I made a button to insert a picture, and it loaded the pictureBox with the image then it puts it in the richTextBox then it clears the pictureBox control.
Here is the code.
private void InsertPicture_Click(object sender, EventArgs e)
{
{
if (openFileDialog4.ShowDialog() == DialogResult.OK)
{
// Show the Open File dialog. If the user clicks OK, load the
// picture that the user chose.
pictureBox2.Load(openFileDialog4.FileName);
Clipboard.SetImage(pictureBox2.Image);
pictureBox2.Image = null;
this.richTextBox1.Paste();
}
}
}
After inserting the code to do it with the clipboard, type in Clipboard.Clear();. It works well and it doesn't clear everything, only the item last added to the clipboard.
Full Code:
private void addPictureToRTB()
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Pictures|*.png" })
{
if (ofd.ShowDialog() == DialogResult.OK)
{
ClipBoard.SetImage(Image.FromFile(ofd.FileName));
richTextBox.Paste();
Clipboard.Clear();
}
}
}
Then reference this function where you need to.
Several hours surfing for solution to insert image without loosing quality and fixed the gray background with transparent image/png
// assuming the image is in your Resources
var img = Resources.ImageWithTransparentBckgrnd;
var g = Graphics.FromImage(img);
using (var ms = new MemoryStream())
{
img.Save(ms, ImageFormat.Png);
IntPtr ipHdc = g.GetHdc();
Metafile mf = new Metafile(ms, ipHdc);
g = Graphics.FromImage(mf);
g.FillEllipse(Brushes.White, 0, 0, 16, 16); // size you want to fill in
g.Dispose();
mf.Save(ms, ImageFormat.Png);
IDataObject dataObject = new DataObject();
dataObject.SetData("PNG", false, ms);
Clipboard.SetDataObject(dataObject, false);
richTextBox1.Paste();
SendKeys.Send("{RIGHT}");
richTextBox1.Focus();
}

Clipboard fail to restore data with setdataobject

I got a problem with restoring the data here is the code if you read the comments then I ll think you ll understand the problem, and hopefuly know how to fix this.
var oldclip = System.Windows.Clipboard.GetDataObject(); //Here we save the clipboard
var oldpoint = CursorPosition;
CursorPosition = new System.Drawing.Point((Convert.ToInt32((rect.Width - rect.X) * 0.45) + rect.X), Convert.ToInt32((rect.Height - rect.Y) * 0.75) + rect.Y);
DoLeftMouseClick();
SetForegroundWindow(hwnd);
System.Threading.Thread.Sleep(20);
System.Windows.Forms.SendKeys.SendWait("^a^c{ESCAPE}"); // here we go select all text and then copy it to the clipboard
if (System.Windows.Clipboard.GetDataObject().GetDataPresent(DataFormats.Text)) //if the clipboard has text then we do something with it to get that info in the blabla here
{
//...blabla //
}
System.Windows.Clipboard.SetDataObject(oldclip); // HERE I want to restore the clipboard but that fails! After this when I CTRL+P(paste) then it returns nothing,(while it should still have the same "oldclip" data no??
EDIT: I got a better idea how to explain my problem. Lets say I got 2 buttons, button save & button restore.
We got a variable:
IDataObject oldclip;
Button save code is:
oldclip = System.Windows.Clipboard.GetDataObject();
The we got the restore button code
System.Windows.Clipboard.SetDataObject(oldclip);
Now I copy some text "randomtext123". I press the save button. Then I go and copy some other text "otherrandomtext".
Now if I press the restore button, I want the clipboard data to be "randomtext123" again but this doesn t happen.(Because if I paste after the resto button it doesn t do anything, like there is nothing on the clipboard). Hope you understand the problem better now :)
This should produce the desired result:
public class ClipboardBackup
{
Dictionary<string, object> contents = new Dictionary<string,object>();
public void Backup()
{
contents.Clear();
IDataObject o = Clipboard.GetDataObject();
foreach (string format in o.GetFormats())
contents.Add(format, o.GetData(format));
}
public void Restore()
{
DataObject o = new DataObject();
foreach (string format in contents.Keys)
{
o.SetData(format, contents[format]);
}
Clipboard.SetDataObject(o);
}
}
P.S. you might not want to do this. See this answer: https://stackoverflow.com/a/2579846/305865
Per the MSDN documentation, if you want to use the system clipboard, you must set the permission to AllClipboard:
for permission to access data on the system Clipboard. Associated
enumeration: AllClipboard
I just tested, and running this code in your codebase will fix the problem:
UIPermission clipBoard = new UIPermission(PermissionState.None);
clipBoard.Clipboard = UIPermissionClipboard.AllClipboard;

Categories

Resources