【发布时间】:2015-03-18 01:52:13
【问题描述】:
我有一个窗口,我只知道我需要激活、调整大小并放置在屏幕左上角的标题(例如记事本)。 所以在对 MSDN 和论坛进行了一些研究之后,我发现了一些应该实现这一点的功能。我使用 FindWindow 按标题获取句柄,然后使用 GetWindowPlacement 查看记事本是否最小化(如果没有,则我只使用 AppActivate,如果没有最小化则只需要激活它)。但是,如果窗口被最小化,我会尝试使用 SetWindowPlacement 在一个命令中激活、调整大小和移动它。 这是我的代码:
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function FindWindow( _
ByVal lpClassName As String, _
ByVal lpWindowName As String) As IntPtr
End Function
<DllImport("user32.dll")> _
Private Shared Function GetWindowPlacement(ByVal hWnd As IntPtr, ByRef lpwndpl As WINDOWPLACEMENT) As Boolean
End Function
<DllImport("user32.dll")> _
Private Shared Function SetWindowPlacement(ByVal hWnd As IntPtr, ByRef lpwndpl As WINDOWPLACEMENT) As Boolean
End Function
Private Structure RECT
Public Left As Integer
Public Top As Integer
Public Right As Integer
Public Bottom As Integer
Public Sub New(ByVal X As Integer, ByVal Y As Integer, ByVal X2 As Integer, ByVal Y2 As Integer)
Me.Left = X
Me.Top = Y
Me.Right = X2
Me.Bottom = Y2
End Sub
End Structure
Private Structure WINDOWPLACEMENT
Public Length As Integer
Public flags As Integer
Public showCmd As ShowWindowCommands
Public ptMinPosition As POINTAPI
Public ptMaxPosition As POINTAPI
Public rcNormalPosition As RECT
End Structure
Enum ShowWindowCommands As Integer
Hide = 0
Normal = 1
ShowMinimized = 2
Maximize = 3
ShowMaximized = 3
ShowNoActivate = 4
Show = 5
Minimize = 6
ShowMinNoActive = 7
ShowNA = 8
Restore = 9
ShowDefault = 10
ForceMinimize = 11
End Enum
Public Structure POINTAPI
Public X As Integer
Public Y As Integer
Public Sub New(ByVal X As Integer, ByVal Y As Integer)
Me.X = X
Me.Y = Y
End Sub
End Structure
实际执行在这里:
Dim wp As WINDOWPLACEMENT
wp.Length = Marshal.SizeOf(wp)
GetWindowPlacement(FindWindow(Nothing, "Notepad"), wp)
If wp.showCmd = ShowWindowCommands.ShowMinimized Then
Dim wp2 As WINDOWPLACEMENT
wp2.showCmd = ShowWindowCommands.ShowMaximized
wp2.ptMinPosition = wp.ptMinPosition
wp2.ptMaxPosition = New POINTAPI(0, 0)
wp2.rcNormalPosition = New RECT(0, 0, 816, 639) 'this is the size I want
wp2.flags = wp.flags
wp2.Length = Marshal.SizeOf(wp2)
SetWindowPlacement(FindWindow(Nothing, "Notepad"), wp2)
Else
AppActivate("Notepad")
所以我尝试运行它,但它只是激活了窗口,而矩形也应该调整它的大小。那么我做错了什么?有没有更简单的方法来实现这一切?抱歉发了这么长的帖子
【问题讨论】:
-
使用您的代码,在您将窗口从
maximized恢复到normal后,矩形的效果就会发生。将wp2.showCmd = ShowWindowCommands.ShowMaximized更改为wp2.showCmd = ShowWindowCommands.Normal。您不希望窗口最大化。 -
你忽略了错误检查