如何打開Interaction.InputBox到窗體的中心?我知道有一個代碼的位置的輸入框輸入框位置
Interaction.InputBox("Question?", "Title", "Default Text", x,y);
我將使用此InputBox以不同的大小不同的形式。有沒有辦法打開窗體中心的InputBox?或者我必須在每個表單上分別定位它們?
是否有可能也重新定位的InputBox的OKbutton和Cancelbutton?
如何打開Interaction.InputBox到窗體的中心?我知道有一個代碼的位置的輸入框輸入框位置
Interaction.InputBox("Question?", "Title", "Default Text", x,y);
我將使用此InputBox以不同的大小不同的形式。有沒有辦法打開窗體中心的InputBox?或者我必須在每個表單上分別定位它們?
是否有可能也重新定位的InputBox的OKbutton和Cancelbutton?
如果您想要完全自定義,那麼創建自己的表單是Fabio評論中指出的最佳方式。
不過,如果你只是想大致中心的框,你會做了很多次,那麼你可以編寫自己的擴展方法來展現,併爲您的輸入框的位置:從
public static class FormExtensions
{
public static string CentredInputBox(this Form form, string prompt, string title = "", string defaultResponse = "")
{
const int approxInputBoxWidth = 370;
const int approxInputBoxHeight = 158;
int left = form.Left + (form.Width/2) - (approxInputBoxWidth/2);
left = left < 0 ? 0 : left;
int top = form.Top + (form.Height/2) - (approxInputBoxHeight/2);
top = top < 0 ? 0 : top;
return Microsoft.VisualBasic.Interaction.InputBox(prompt, title, defaultResponse, left, top);
}
}
用法在表單中:
this.CentredInputBox("MyPrompt", "MyTitle", "MyDefaultResponse");
它並不完美,因爲如果盒子比正常大由於某種原因,那麼就不太在中心,我認爲它的大小是可變的,這取決於很多文字是如何在它。但是,在正常使用情況下不應該太遠。
要使InputBox
居中,您可以嘗試使用Win32
函數來處理它。此代碼對你的作品:
[DllImport("user32")]
private static extern int SetWindowPos(IntPtr hwnd, IntPtr afterHwnd, int x, int y, int cx, int cy, int flag);
[DllImport("user32")]
private static extern IntPtr FindWindow(string className, string caption);
[DllImport("user32")]
private static extern int GetWindowRect(IntPtr hwnd, out RECT rect);
//RECT structure
public struct RECT {
public int left, top, right, bottom;
}
public void ShowCenteredInputBox(string prompt, string title, string defaultReponse){
BeginInvoke((Action)(() => {
while (true) {
IntPtr hwnd = FindWindow(null, title + "\n\n\n");//this is just a trick to identify your InputBox from other window with the same caption
if (hwnd != IntPtr.Zero) {
RECT rect;
GetWindowRect(hwnd, out rect);
int w = rect.right - rect.left;
int h = rect.bottom - rect.top;
int x = Left + (Width - w)/2;
int y = Top + (Height - h)/2;
SetWindowPos(hwnd, IntPtr.Zero, x, y, w, h, 0x40);//SWP_SHOWWINDOW = 0x40
break;
}
};
}));
Microsoft.VisualBasic.Interaction.InputBox(prompt, title + "\n\n\n", defaultResponse,0,0);
}
當然你也可以改變你的InputBox
但它是非常討厭和麻煩,我們可以說,這不是簡單的按鈕,標籤和文本框的位置。爲您推薦的解決方案是在System.Windows.Forms.Form
中創建新標準表單,爲其添加控件並使用方法ShowDialog()
來顯示您的表單。。當然,它需要更多的代碼才能完成,但它可以讓您完全自定義外觀和行爲。
您可以設置InputBox的起始位置。有一個屬性
InputBox ib = new InputBox();
ib.StartPosition = FormStartPosition.CenterParent;
作爲FormStartPosition是一個枚舉,您可以從中選擇您想要的位置!
很確定它是一個靜態類... – Jack
您可以ipsiply使用-1作爲x和y: Interaction.InputBox(「Question?」,「Title」,「Default Text」,-1,-1);
創建自己的窗體並根據需要放置'TextBox','Label'和'Buttons'。然後,你總是可以在每種形式中調用它作爲'inputForm.StartPosition = FormStartPosition.CenterParent;'然後'inputForm.ShowDialog(this);' – Fabio