代码改变世界

winform控件随窗口自适应

2020-11-09 09:42  idea555  阅读(670)  评论(0)    收藏  举报

private int ii = 1;
private int textBox_left = 0;
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
//DataTable dt = new DataTable();
//dt.Columns.Add("name", typeof(string));
//dt.Columns.Add("age", typeof(string));
//dt.Columns.Add("sex", typeof(string));
////假设这里绑定了3列的datatable

//this.dataGridView1.DataSource = dt;
//int width = this.dataGridView1.Width;
//int avgWidth = width / dt.Columns.Count;//求出每一列的header宽度
//for (int i = 0; i < this.dataGridView1.Columns.Count; i++)
//{
// this.dataGridView1.Columns[i].Width = avgWidth;//设置每一列的宽度
//}

this.dataGridView1.Columns[0].Width = 80;
this.dataGridView1.Columns[1].Width = 80;
this.dataGridView1.Columns[2].Width = 80;
this.dataGridView1.Columns[3].Width = this.dataGridView1.Width - 240;
}

private void button1_Click(object sender, EventArgs e)
{
int width = this.Width;
int height = this.Height;
MessageBox.Show(width.ToString() + "," + height.ToString());

int width1 = dataGridView1.Width;
int height1 = dataGridView1.Height;
MessageBox.Show(width1.ToString() + "," + height1.ToString());


}

private void button2_Click(object sender, EventArgs e)
{
dataGridView1.Width = dataGridView1.Width + 100;
dataGridView1.Height = dataGridView1.Height + 100;
}

const int WM_SYSCOMMAND = 0x112;
const int SC_CLOSE = 0xF060;
const int SC_MINIMIZE = 0xF020;
const int SC_MAXIMIZE = 0xF030;
const int SC_RESTORE = 61728;
//窗体按钮的拦截函数
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_SYSCOMMAND)
{
if (m.WParam.ToInt32() == SC_RESTORE)
{
//log.Info("窗口还原!");
}
if (m.WParam.ToInt32() == SC_MINIMIZE) //拦截最小化按钮
{
//这里写操作代码
//log.Info("点击最小化按钮!");
}
if (m.WParam.ToInt32() == SC_MAXIMIZE) //拦截窗体最大化按钮
{
//log.Info("点击最大化按钮!");
//.....................
//dataGridView1.Width = dataGridView1.Width + 500;
//dataGridView1.Height = dataGridView1.Height + 500;

}
if (m.WParam.ToInt32() == SC_CLOSE) //拦截窗体关闭按钮
{

//log.Info("点击窗口关闭按钮!");
}


}
base.WndProc(ref m);


}

private void Form1_Resize(object sender, EventArgs e)
{
int width = this.Width;
int height = this.Height;


if (ii == 1)
{
textBox_left = textBox2.Left;
ii += 1;
}
//MessageBox.Show(width.ToString() + "," + height.ToString());
//MessageBox.Show((width - 800).ToString());
textBox2.Left = textBox_left + (width -800);
textBox2.Top = textBox2.Top;
//MessageBox.Show(left.ToString() + "," + top.ToString());

this.dataGridView1.Columns[3].Width = this.dataGridView1.Width - 240;
}