A
Andrei P.
Is Clipboard available in CF?
I need to paste a text to TextBox.
Any ideas?
Andrei
I need to paste a text to TextBox.
Any ideas?
Andrei
#endregion -----------------------------------------------------------------Mark Reddick said:I found some code (don't remember where now) for a class that allows
accessing the actual device clipboard by using the device's API DLL's
(P/Invoke?). Just copy this code into it's own class file, reference the
class in your form and you can then use it to manipulate the clipboard. It
does, however, use unsafe code so you'll have to use the compiler switch to
allow that.
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace My.Namespace.Util
{
/// <summary>
/// Summary description for Clipboard.
/// </summary>
public class Clipboard
{
#region Win32
API ------------------------------------------------------------
private const uint CF_UNICODETEXT = 13;
[DllImport("Coredll.dll")]
private static extern bool OpenClipboard(IntPtr hWndNewOwner);
[DllImport("Coredll.dll")]
private static extern bool CloseClipboard();
[DllImport("Coredll.dll")]
private static extern bool EmptyClipboard();
[DllImport("Coredll.dll")]
private static extern bool IsClipboardFormatAvailable(uint uFormat);
[DllImport("Coredll.dll")]
private static extern IntPtr GetClipboardData(uint uFormat);
[DllImport("Coredll.dll")]
private static extern IntPtr SetClipboardData(uint uFormat, IntPtr hMem);
[DllImport("Coredll.dll")]
private static extern IntPtr LocalAlloc(int uFlags, int uBytes);
#endregion -------------------------------------------------------------------
#region
Clipboard ------------------------------------------------------------
private static IntPtr hMem = IntPtr.Zero;
public static bool IsDataAvailable
{
get
{
return IsClipboardFormatAvailable(CF_UNICODETEXT);
}
}
public unsafe static bool SetData(string strText)
{
if (OpenClipboard(IntPtr.Zero) == false)
{
return false;
}
hMem = LocalAlloc(0, ((strText.Length + 1) * sizeof(char)));
if (hMem.ToInt32() == 0)
{
return false;
}
CopyToPointer(hMem, strText);
EmptyClipboard();
SetClipboardData(CF_UNICODETEXT, hMem);
CloseClipboard();
return true;
}
public static string GetData()
{
IntPtr hData;
string strText;
if (IsDataAvailable == false)
{
return null;
}
if (OpenClipboard(IntPtr.Zero) == false)
{
return null;
}
hData = GetClipboardData(CF_UNICODETEXT);
if (hData.ToInt32() == 0)
{
return null;
}
strText = ConvertToString(hData);
CloseClipboard();
return strText;
}
private unsafe static void CopyToPointer(IntPtr dest, string src)
{
int x;
char* pDest = (char*) dest.ToPointer();
for (x = 0; x < src.Length; x++)
{
pDest[x] = src[x];
}
pDest[x] = '\0'; // Add the null terminator.
}
private unsafe static string ConvertToString(IntPtr src)
{
int x;
char* pSrc = (char*) src.ToPointer();
StringBuilder sb = new StringBuilder();
for (x = 0; pSrc[x] != '\0'; x++)
{
sb.Append(pSrc[x]);
}
return sb.ToString();
}