Copy empty string using Clipboard.SetText(string)

风格不统一 提交于 2019-11-28 07:36:50

问题


Clipboard.SetText("") throws me an error - "Value cannot be null". So how do I copy an empty string using Clipboard.SetText?

I have already done Clipboard.Clear(). It does clear the clipboard, but it doesn't help me to paste an empty string

Any suggestions?


回答1:


If you try to save null or an empty string using Clipboard.SetText it will never work.

See Clipboard.SetText Method (String) (MSDN). It mentions ArgumentNullException is thrown if the text is null or Empty for Clipboard.SetText.

Hence you cannot achieve what you are trying to achieve.




回答2:


I think you need to do

Clipboard.Clear()

From MSDN

Clears any data from the system Clipboard.




回答3:


See Clipboard.Clear Method (System.Windows.Forms) (MSDN).

Clipboard.Clear();

will clear the clipboard, so you will "paste" an empty string.




回答4:


Reference PresentationCore and call System.Windows.Clipboard.SetText(string) instead of System.Windows.Forms.Clipboard.SetText(string). I used clipview to verify that System.Windows.Clipboard.SetText(""); (which throws no exception) stores the empty string into the clipboard.

This method it saves you from having to conditionally call Clear() or SetText() depending on what string you are trying to effectively set into clipboard. This is especially useful if you’re trying to write code to set the clipboard to any string value without knowing ahead of time whether or not the empty string needs to be supported. I.e., this method enables you to avoid treating the empty string like a special case (IMO, it shouldn’t be a special case because that’s just confusing).

Additionally, as can be seen with clipview, Clear() actually empties out the clipboard instead of placing an empty string in it. Calling System.Windows.Clipboard.SetText("") actually puts an empty string value into clipboard. When you paste, the target application can tell the difference and actually behave differently if it wants to.



来源:https://stackoverflow.com/questions/11952960/copy-empty-string-using-clipboard-settextstring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!