【问题标题】:c# focus window of a runing programc# 正在运行的程序的焦点窗口
【发布时间】:2014-10-24 01:22:43
【问题描述】:

我想从我的 c# 应用程序中集中一个程序。我搜索了很多并找到了一些示例。但是我得到了错误。我正在使用 Visual Studio。ShowWindow(hWnd, SW_HIDE); 行给了我一个错误"showwindow(system.IntPtr,int) has some invalid argument" 请问这段代码的问题在哪里

[DllImport("user32.dll")]
        internal static extern IntPtr SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

 private void FocusProcess()
        {
            int hWnd;
            Process[] processRunning = Process.GetProcesses();
            foreach (Process pr in processRunning)
            {
                if (pr.ProcessName == "notepad")
                {
                    hWnd = pr.MainWindowHandle.ToInt32();
                    ShowWindow(hWnd, 3);//error line
                }
            }
        }

【问题讨论】:

  • 你为什么打电话给ToInt32()MainWindowHandle 已经为您提供了正确类型的值。类型转换是您收到错误的原因:它是不兼容的类型。

标签: c# setfocus user32


【解决方案1】:

您将 hWnd 声明为 int。但是 ShowWindow 函数需要一个 IntPtr。因为 pr.MainWindowHandle 是一个 IntPtr,你只需要将它用作 hWnd。 顺便提一句。如果您希望此窗口位于最顶层,则应调用 SetForegroundWindow。

    [DllImport("user32.dll")]
    internal static extern IntPtr SetForegroundWindow(IntPtr hWnd);

    [DllImport("user32.dll")]
    internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); //ShowWindow needs an IntPtr

    private static void FocusProcess()
    {
        IntPtr hWnd; //change this to IntPtr
        Process[] processRunning = Process.GetProcesses();
        foreach (Process pr in processRunning)
        {
            if (pr.ProcessName == "notepad")
            {
                hWnd = pr.MainWindowHandle; //use it as IntPtr not int
                ShowWindow(hWnd, 3);
                SetForegroundWindow(hWnd); //set to topmost
            }
        }
    }

【讨论】:

  • “记事本”可能需要用大写字母 N 拼写?或者也许更好地使用一些不区分大小写的比较?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-04
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 2012-08-30
相关资源
最近更新 更多