SetWindowPos出错

时间:2014-10-28 15:46:57

标签: winapi c++-cli

我试图编写简单的代码来更改应用程序(记事本)窗口位置。记事本应该在后台运行(只有1个实例)。

我正在使用Process::GetProcessesByName( "notepad")来获取进程ID, 和myProcess->MainWindowHandle来获取记事本窗口。

现在我试图通过将HWND句柄传递给SetWindowPos来改变窗口大小,

我不确定如何正确地做到这一点(搜索网络没有找到明确的新手答案)

我试过第一次尝试:

HWND hwnd =  myProcess->MainWindowHandle;
             SetWindowPos(hwnd , 
                 HWND_TOP, 
                 100, 
                 100, 
                 0, 0,          // Ignores size arguments. 
                 SWP_NOSIZE); 

这让我

Compile error:  error C2440: 'initializing' : cannot convert from 'System::IntPtr' to 'HWND'

然后我尝试投射并传递作为参考:

HWND hwnd =  (HWND)&myProcess->MainWindowHandle;
SetWindowPos(&hwnd , 
         HWND_TOP, 
         100, 
         100, 
         0, 0,          // Ignores size arguments. 
         SWP_NOSIZE); 

       }

错误:

Compile error:  error C2664: 'SetWindowPos' : cannot convert parameter 1 from 'HWND *' to 'HWND'

请参阅下面的完整代码:

#include "StdAfx.h"
#include <windows.h>
#include <iostream>
#include <string>  

#using <System.dll>
using namespace System;
using namespace System::Diagnostics;
int main()
{

      array<Process^>^myProcesses = Process::GetProcessesByName( "notepad");
      if ( myProcesses->Length == 0 )
            Console::WriteLine( "Could not find notepad processes on local computer." );
      Collections::IEnumerator^ myEnum = myProcesses->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         Process^ myProcess = safe_cast<Process^>(myEnum->Current);
         Console::Write( "Process Name : {0}  Process ID : {1}  HandleCount : {2}\n", myProcess->ProcessName, myProcess->Id, myProcess->HandleCount );
         Console::Write( "Main window Title : {0}  MainWindowHandle : {1}", myProcess->MainWindowTitle, myProcess->MainWindowHandle );

//HWND hwnd =  myProcess->MainWindowHandle; //1st try
     //          SetWindowPos(hwnd , 
  //               HWND_TOP, 
  //               100, 
  //               100, 
  //               0, 0,          // Ignores size arguments. 
  //               SWP_NOSIZE); 

        HWND hwnd =  (HWND)&myProcess->MainWindowHandle;//2nd try
        SetWindowPos(&hwnd , 
                 HWND_TOP, 
                 100, 
                 100, 
                 0, 0,          // Ignores size arguments. 
                 SWP_NOSIZE); 

               }
      }   
}

1 个答案:

答案 0 :(得分:1)

您将地址发送到SetWindowsPos函数的第一个参数,但此函数需要HWND值。你知道在C ++中:

  • &amp; variable =返回变量的地址,其中存储值
  • variable =变量的返回值

Visual C ++ Intellisense或工具提示为您提供原型。

BOOL SetWindowsPos(HWND, HWND, int, int, int, int, UINT);

编辑:正如评论中所说,这一行:

HWND hwnd = (HWND)&myProcess->MainWindowHandle;

错了,你必须这样做:

HWND hwnd = (HWND)myProcess->MainWindowHandle.ToPointer();

ToPointer 方法文档:http://msdn.microsoft.com/fr-fr/library/system.intptr.topointer(v=vs.110).aspx