Clipboard fail to restore data with setdataobject - c#

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;

Related

Scrolling list with multiple objects

I have been making a form to let the user save his progress. There are 6 virtual slots which contain different save files read from a folder. I want to have the same set up just with a scrollbar to let user scroll through save files, in case he has more than 6 made.
The set up is: picturebox which loads save file when clicked, label for file name and for file date, picturebox to delete the save file, and a panel underneath to save file when the slot is clicked.
Below is the code I use to load in 6 save files. (I will get the date by reading the save file start as it contains the date, but I have not done that part yet).
private void loadsavestoscreen()
{
string filename;
string extension;
string locpath = #"C:\test";
String[] allfiles = System.IO.Directory.GetFiles(locpath, "*.*", System.IO.SearchOption.TopDirectoryOnly);
int counter = 0;
foreach (String file in allfiles)
{
if (counter == 6 || counter == allfiles.Length - 1)
{ labelcheck(); break; }
if ((extension = Path.GetExtension(file)) == ".dat")
{
filename = Path.GetFileNameWithoutExtension(file);
//Console.WriteLine(filename);
changelbl(counter, filename);
counter++;
}
}
}
'labelcheck' checks if the text is correct, if not it hides the label.
'lblchange' changes the name of the label on the correct slot.
My question is: How would I implement a scrollbar to allow the user to scroll through more save files when there is more than 6?
Here's a snippet of the form:
I am slightly new to programming so my apologies if I've made some obvious errors. Thanks for any help.
Without a list object or a container this is not very easy to solve.
I suggest you to use a DataGridView or a ListView object. You can easily add your file entries as objects to these lists. They have an option Scrollable, which you can set true or false.
I would also create a class for that save file entries (storing label/image position and contents) and add them to your DataGridView or ListView.
If you want to know how to add images to those controls:
How do add image to System.Windows.Forms.ListBox?

How can I add an image to my sheet without being prompted to replace contents of the (empty) destination cells (EPPlus)?

When I open the Excel file I generate using EPPlus (C#), I get "Do you want to replace the contents of the destination cells in [... .xlsx]PivotTable?"
As you can see in the screen shot below, there is nothing in the cell where I want the image to display. Even when I push the image beyond the outer edge of the PivotTable, I get this message (I had been placing beneath column C/3). When I select yes to the dialog quoted above, the image is finally placed on the sheet (if I select "no" it is not added), and the sheet looks like this:
This is the code I'm using to add the image:
int imageCol = _grandTotalsColumnPivotTable + 1; // -1; <= I really want it to be this
AddImage(pivotTableWorksheet, 1, imageCol);
. . .
private void AddImage(ExcelWorksheet oSheet, int rowIndex, int colIndex)
{
var excelImage = oSheet.Drawings.AddPicture("PRO*ACT Logo", _logo);
excelImage.From.Column = colIndex - 1;
excelImage.From.Row = rowIndex - 1;
excelImage.SetSize(130, 100);
excelImage.From.ColumnOff = Pixel2MTU(2);
excelImage.From.RowOff = Pixel2MTU(2);
}
public int Pixel2MTU(int pixels)
{
int mtus = pixels * 9525;
return mtus;
}
How can I either get the message to not display (programmatically, this can't be something the user needs to do) and "just do it" or let it know that there is nothing in that location, anyway?
UPDATE
This is apparently not the problem; I tried to delete this post, but can't, since it has an answer. Even when I comment out the writing of the image, I get it. And trying to prevent messages like so:
_xlApp.DisplayAlerts = false;
...does not work, either - I still get it.
Apparently the problem is elsewhere, but I don't know where.
UPDATE 2
It was a case of hidden data underneath the PivotTable; once I got rid of that, the problem went away. IOW, the problem was with my code, not with EPPlus.
I use this code to add an image to Excel. It does not asks me to replace content. But I do not use PivotTables. Maybe that would make a difference.
using (System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("test.png")))
{
var excelImage = ws.Drawings.AddPicture("My Logo", image);
excelImage.SetPosition(1, 0, 5, 0);
}

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();
}

Couldn't assign value in FileUpload tool

I grabbed the value from database and I am trying to assign those values in Edit Form. But the only problem is with the FileUpload. It don't take the value. Can anyone suggest me what I'm missing here
private void EditForDataByID(int TitleId)
{
ReadmoreController objFormController = new ReadmoreController();
ReadMoreInfo objInfo = objFormController.GetListObjectOfAllArticle(TitleId);
if (objInfo != null)
{
TextTitle.Text = objInfo.Title;
txtSummary.Text = objInfo.Summary;
TextDate.Text = objInfo.Date.ToString();
//FileUpload1.FileName=objInfo.Image; I even tried this but it doesn't work
FileUpload1 = objInfo.Image;
Session["TitleId"] = TitleId;
ListDiv.Visible = false;
form.Visible = true;
BindGrid();
}
}
For client security reason you can not assign value to FileUploadControl as it could cause the uploading of unwanted files from client machine. So let the use pick the file to upload.
If it is allowed then one can steel the important files from client machine like c:\PersonalPasswords
Edit Based on comments
If you need to ensure that user has selected an Image and does not need to change it then you can use a image control and assign image to it. Use the same image control to find if the image is selected or not.

Create a VS2010 Addin to collapse every methods of my active document

I'm looking for the source code to collapse every methods of my active document using the VS2010 Addin.
For the moment I parse the text content of the document trying to match if the line is a method signature. If it is the case, I collapse the method.
TextSelection selection = (TextSelection)_applicationObject.ActiveDocument.Selection;
var editPoint = selection.ActivePoint.CreateEditPoint();
editPoint.MoveToLineAndOffset(1, 1);
while (!editPoint.AtEndOfDocument)
{
editPoint.StartOfLine();
var line = editPoint.GetText(editPoint.LineLength).TrimStart();
if (line.StartsWith("public"))
{
selection.MoveToLineAndOffset(editPoint.Line, 1);
_applicationObject.ExecuteCommand("Edit.ToggleOutliningExpansion");
}
// go to the next line
}
Does anyone could tell me if I'm on the good way or if there is an easiest way ?
Maybe I asked not so well my question. My real goal was to collapse all the code : properties, methods, comments with ///, using; but not the regions.
Here is one solution :
// reduce everything like Ctrl+M+O
_applicationObject.ExecuteCommand("Edit.CollapsetoDefinitions");
// save the cursor position
TextSelection selection = (TextSelection)_applicationObject.ActiveDocument.Selection;
var selectedLine = selection.ActivePoint.Line;
var selectedColumn = selection.ActivePoint.DisplayColumn;
// open the regions
selection.StartOfDocument();
while (selection.FindText("#region", (int)vsFindOptions.vsFindOptionsMatchInHiddenText))
{
// do nothing since FindText automatically expands any found #region
}
// put back the cursor at its original position
selection.MoveToDisplayColumn(selectedLine, selectedColumn);
I hope this could help

Categories

Resources