Member 11776570 Ответов: 1

Функция не работает...


A call to PInvoke function 'Testing-Class!Testing_Class.Form1::GetClassName' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.


Что я уже пробовал:

Я должен добавить это
[DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern long GetClassName(IntPtr hwnd, StringBuilder lpClassName, long nMaxCount);


[DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern long GetWindowText(IntPtr hwnd, StringBuilder lpString, long cch);


string GetCaptionOfWindow(IntPtr hwnd)
        {
            string caption = "";
            StringBuilder windowText = null;
            try
            {
                int max_length = GetWindowTextLength(hwnd);
                windowText = new StringBuilder("", max_length + 5);
                GetWindowText(hwnd, windowText, max_length + 2); // Its is giving error here

                if (!String.IsNullOrEmpty(windowText.ToString()) && !String.IsNullOrWhiteSpace(windowText.ToString()))
                    caption = windowText.ToString();
            }
            catch (Exception ex)
            {
                caption = ex.Message;
            }
            finally
            {
                windowText = null;
            }
            return caption;
        }

        string GetClassNameOfWindow(IntPtr hwnd)
        {
            string className = "";
            StringBuilder classText = null;
            try
            {
                int cls_max_length = 1000;
                classText = new StringBuilder("", cls_max_length + 5);
                GetClassName(hwnd, classText, cls_max_length + 2);// Its is giving error here

                if (!String.IsNullOrEmpty(classText.ToString()) && !String.IsNullOrWhiteSpace(classText.ToString()))
                    className = classText.ToString();
            }
            catch (Exception ex)
            {
                className = ex.Message;
            }
            finally
            {
                classText = null;
            }
            return className;
        }

1 Ответов

Рейтинг:
5

Alan N

Рабочий пример таков

public static String GetText(IntPtr hWnd) {
  // Allocate correct StringBuilder capacity 
  Int32 length = GetWindowTextLength(hWnd);
  StringBuilder sb = new StringBuilder(length + 1);
  GetWindowText(hWnd, sb, sb.Capacity);
  return sb.ToString();
}


Емкость StringBuilder устанавливается для длины текста+1, чтобы разрешить нулевой Терминатор, и очень важно, что метод GetWindowText получает правильный размер. Не добавляйте свою собственную прокладку! Маршаллер взаимодействия очень умен и рассматривает StringBuilder как массив символов, а sb.Capacity-это длина этого массива.

Алан.