Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

.net - How to set HTML to clipboard in C#?

I want to put rich text in HTML on the clipboard so when the users paste to Word, it will include the source HTML formatting.

Using the Clipboard.SetText method doesn't work.

Also, I would like that if users paste into a rich editor like Word it will paste formatted text, and if they paste into a plain editor like Notepad it will paste plain text.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When setting HTML text, you need to provide a header with additional information to what fragment of the html you actually want to paste while being able to provide additional styling around it:

Version:0.9
StartHTML:000125
EndHTML:000260
StartFragment:000209
EndFragment:000222
<HTML>
<head>
<title>HTML clipboard</title>
</head>
<body>
<!–StartFragment–><b>Hello!</b><!–EndFragment–>
</body>
</html>

With the header (and correct indexes), calling Clipboard.SetText with TextDataFormat.Html will do the trick.

To handle HTML and plain text pastes, you can’t use the Clipboard.SetText method, as it clears the clipboard each time it’s called; you need to create a DataObject instance, call its SetData method once with HTML and once with plain text, and then set the object to clipboard using Clipboard.SetDataObject.

Update

See "Setting HTML/Text to Clipboard revisited" for more details and ClipboardHelper implementation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...