コード例 #1
0
        public bool TryGetText(out string text)
        {
            if (!Open())
            {
                text = null;
                return(false);
            }

            try
            {
                var formats = new[] { Win32ClipboardFormat.CF_UNICODETEXT };
                int format  = Win32API.GetPriorityClipboardFormat(formats, formats.Length);
                if (format <= 0)
                {
                    text = null;
                    return(false);
                }

                IntPtr dataHandle = Win32API.GetClipboardData((Win32ClipboardFormat)format);
                if (dataHandle == IntPtr.Zero)
                {
                    text = null;
                    return(false);
                }

                IntPtr dataPtr = Win32API.GlobalLock(dataHandle);
                if (dataPtr == IntPtr.Zero)
                {
                    text = null;
                    return(false);
                }

                try
                {
                    text = Marshal.PtrToStringUni(dataPtr);
                    return(true);
                }
                finally
                {
                    Win32API.GlobalUnlock(dataHandle);
                }
            }
            finally
            {
                Win32API.CloseClipboard();
            }
        }