【问题标题】:Windows API not working in WPF?Windows API 在 WPF 中不起作用?
【发布时间】:2016-01-25 11:12:48
【问题描述】:

似乎GetClassName 和其他一些 Windows API 在 WPF 中根本不起作用,而是使应用程序崩溃(无异常)。复制它非常简单。以下是完整代码(创建新的 WPF 应用程序后将其粘贴到 Window1 的代码隐藏中):

using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Input;

namespace WpfApplication1
{
  /// <summary>
  /// Interaction logic for MainWindow.xaml
  /// </summary>
  public partial class MainWindow : Window
  {
    [DllImport("user32.dll")]
    static extern IntPtr WindowFromPoint(POINT p);

    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
      public int X, Y;
    }

    public MainWindow()
    {
      InitializeComponent();
    }

    private void Window_MouseDown(object sender, MouseButtonEventArgs e)
    {
      var Pos = e.GetPosition(this);
      var WindowUnderMouse = WindowFromPoint(new POINT() { X = (int)Pos.X, Y = (int)Pos.Y });
      StringBuilder SB = new StringBuilder();
      GetClassName(WindowUnderMouse, SB, 50);
      MessageBox.Show(SB.ToString());
    }
  }
}

应用程序在GetClassName 呼叫时为我崩溃。我正在使用 VS2015 + .NET 4.5。

或者是我的事?

【问题讨论】:

    标签: c# .net wpf winapi crash


    【解决方案1】:

    GetClassName 运行良好。但是,您调用它不正确。当你写:

    GetClassName(WindowUnderMouse, SB, 50);
    

    您承诺提供长度为 50 的缓冲区。您不这样做。而不是:

    StringBuilder SB = new StringBuilder();
    

    使用

    StringBuilder SB = new StringBuilder(50);
    

    现在,窗口类的最大名称是256。所以我会这样写代码,包括错误检查:

    StringBuilder SB = new StringBuilder(256);
    if (GetClassName(WindowUnderMouse, SB, SB.Capacity) == 0)
        throw new Win32Exception();
    

    【讨论】:

    • 我真的以为StringBuilder 可以根据需要自行扩展。让我试试。
    • 它可以根据需要自行扩展,但只有在调用它的方法时才可以。当您调用 p/invoke 方法时,您将内部缓冲区的地址传递给非托管 Win32 代码。该 Win32 代码看不到 .net 对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 2013-09-17
    • 2010-10-25
    • 2017-04-20
    • 2011-02-26
    相关资源
    最近更新 更多