Click here to Skip to main content
16,015,973 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am using Win32 API functions to register the current program in the Clipboard chain. Below function retrieves the window handle of the current owner of the clipboard. The problem is GetCaptionOfWindow always return null.

C#
[DllImport("user32.dll")]
 public static extern IntPtr GetClipboardOwner();



Pinvoke signature

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern int GetWindowText(IntPtr hWnd, [Out] StringBuilder lpString, int nMaxCount);

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern int GetWindowTextLength(IntPtr hWnd);


What I have tried:

IntPtr ClipboardOwnerHandler = GetClipboardOwner();
string windowTitle = GetCaptionOfWindow(ClipboardOwnerHandler );

private string GetCaptionOfWindow(IntPtr hwnd)
        {
            string caption = "";
            StringBuilder windowText = null;
            try
            {
                int max_length = WindowsApiManager.GetWindowTextLength(hwnd);
                windowText = new StringBuilder("", max_length + 5);
                WindowsApiManager.GetWindowText(hwnd, windowText, max_length + 2);

                if (!String.IsNullOrEmpty(windowText.ToString()) && !String.IsNullOrWhiteSpace(windowText.ToString()))
                    caption = windowText.ToString();
            }
            catch (Exception ex)
            {
                caption = ex.Message;
            }
            finally
            {
                windowText = null;
            }
            return caption;
        }
Posted
Updated 12-Aug-18 1:41am

The GetWindowText function (Windows)[^] requires the second parameter to be the address of a memory buffer. You are passing s StringBuilder reference.
 
Share this answer
 
Comments
Dilan Shaminda 13-Aug-18 5:59am    
I got the method signature from pinvoke.net. it seems to be correct
https://www.pinvoke.net/default.aspx/user32/GetWindowText.html
Richard MacCutchan 13-Aug-18 10:20am    
I don't see how that can work. Unmanaged code does not understand the StringBuilder type.

OK, I stand corrected, I just tried that code and it worked fine.
 
Share this answer
 
Comments
Dilan Shaminda 12-Aug-18 6:54am    
Thanks for the link. I use P/Invoke and my question is why it always return null? I debugged the code but couldn't find the mistake

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900