Приведение IntPtr к Window (управляемому типу) - C#
Формулировка задачи:
Здравствуйте.
Подскажите, пожалуйста, как привести имеющийся указатель на объект известного типа к этому типу?
Я делаю небольшой аддон к Компасу и, судя по документации, надо передать родительское окно моему вспомогательному окну. У меня есть указатель IntPtr на основное окно программы.
Как мне получить тип из указателя?
нужно что-то вроде этого:
public MyWindow(KompasObject kompas)
{
this.Parent = (Window)new IntPtr(kompas.GetHWindow());
}Решение задачи: «Приведение IntPtr к Window (управляемому типу)»
textual
Листинг программы
/// <summary>
/// Отображает эту форму в виде модального диалогового окна с указанным владельцем.
/// </summary>
///
/// <returns>
/// Одно из значений <see cref="T:System.Windows.Forms.DialogResult"/>.
/// </returns>
/// <param name="owner">Любой объект, реализующий <see cref="T:System.Windows.Forms.IWin32Window"/>, которое представляет окно верхнего уровня — будущего собственника модального диалогового окна.</param><exception cref="T:System.ArgumentException">Форма, указанная в параметре <paramref name="owner"/>, совпадает с отображаемой формой.</exception><exception cref="T:System.InvalidOperationException">Отображаемая форма уже отображена. -или- Отображаемая форма отключена. -или- Отображаемая форма не является окном верхнего уровня. -или- Отображаемая в виде диалогового окна форма уже является модальной формой. -или- Текущий процесс не выполняется в интерактивном пользовательском режиме (дополнительные сведения см. в описании свойства <see cref="P:System.Windows.Forms.SystemInformation.UserInteractive"/>).</exception><filterpriority>1</filterpriority><PermissionSet><IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/><IPermission class="System.Security.Permissions.UIPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet>
public DialogResult ShowDialog(IWin32Window owner)
{
if (owner == this)
throw new ArgumentException(SR.GetString("OwnsSelfOrOwner", new object[1]
{
(object) "showDialog"
}), "owner");
if (this.Visible)
throw new InvalidOperationException(SR.GetString("ShowDialogOnVisible", new object[1]
{
(object) "showDialog"
}));
if (!this.Enabled)
throw new InvalidOperationException(SR.GetString("ShowDialogOnDisabled", new object[1]
{
(object) "showDialog"
}));
if (!this.TopLevel)
throw new InvalidOperationException(SR.GetString("ShowDialogOnNonTopLevel", new object[1]
{
(object) "showDialog"
}));
if (this.Modal)
throw new InvalidOperationException(SR.GetString("ShowDialogOnModal", new object[1]
{
(object) "showDialog"
}));
if (!SystemInformation.UserInteractive)
throw new InvalidOperationException(SR.GetString("CantShowModalOnNonInteractive"));
if (owner != null && ((int) UnsafeNativeMethods.GetWindowLong(new HandleRef((object) owner, Control.GetSafeHandle(owner)), -20) & 8) == 0 && owner is Control)
owner = (IWin32Window) ((Control) owner).TopLevelControlInternal;
this.CalledOnLoad = false;
this.CalledMakeVisible = false;
this.CloseReason = CloseReason.None;
IntPtr capture = UnsafeNativeMethods.GetCapture();
if (capture != IntPtr.Zero)
{
UnsafeNativeMethods.SendMessage(new HandleRef((object) null, capture), 31, IntPtr.Zero, IntPtr.Zero);
SafeNativeMethods.ReleaseCapture();
}
IntPtr handle1 = UnsafeNativeMethods.GetActiveWindow();
IntPtr handle2 = owner == null ? handle1 : Control.GetSafeHandle(owner);
IntPtr num = IntPtr.Zero;
this.Properties.SetObject(Form.PropDialogOwner, (object) owner);
Form ownerInternal = this.OwnerInternal;
if (owner is Form)
{
if (owner != ownerInternal)
this.Owner = (Form) owner;
}
try
{
this.SetState(32, true);
this.dialogResult = DialogResult.None;
this.CreateControl();
if (handle2 != IntPtr.Zero)
{
if (handle2 != this.Handle)
{
if (UnsafeNativeMethods.GetWindowLong(new HandleRef((object) owner, handle2), -8) == this.Handle)
throw new ArgumentException(SR.GetString("OwnsSelfOrOwner", new object[1]
{
(object) "showDialog"
}), "owner");
UnsafeNativeMethods.GetWindowLong(new HandleRef((object) this, this.Handle), -8);
UnsafeNativeMethods.SetWindowLong(new HandleRef((object) this, this.Handle), -8, new HandleRef((object) owner, handle2));
}
}
try
{
if (this.dialogResult == DialogResult.None)
Application.RunDialog(this);
}
finally
{
if (!UnsafeNativeMethods.IsWindow(new HandleRef((object) null, handle1)))
handle1 = handle2;
if (UnsafeNativeMethods.IsWindow(new HandleRef((object) null, handle1)) && SafeNativeMethods.IsWindowVisible(new HandleRef((object) null, handle1)))
UnsafeNativeMethods.SetActiveWindow(new HandleRef((object) null, handle1));
else if (UnsafeNativeMethods.IsWindow(new HandleRef((object) null, handle2)) && SafeNativeMethods.IsWindowVisible(new HandleRef((object) null, handle2)))
UnsafeNativeMethods.SetActiveWindow(new HandleRef((object) null, handle2));
this.SetVisibleCore(false);
if (this.IsHandleCreated)
{
if (this.OwnerInternal != null && this.OwnerInternal.IsMdiContainer)
{
this.OwnerInternal.Invalidate(true);
this.OwnerInternal.Update();
}
this.DestroyHandle();
}
this.SetState(32, false);
}
}
finally
{
this.Owner = ownerInternal;
this.Properties.SetObject(Form.PropDialogOwner, (object) null);
}
return this.DialogResult;
}