Hôm nay ngồi coi lại cái tool viết hồi hơn 1 năm trước, tình cờ thấy lại đoạn code hồi xưa mình làm hiệu ứng trượt khi mở form con, sẵn tiện share cách làm cho ai có hứng thú.
Kéo vào Form con 1 Time Control sau đó khai báo các biến, hàm tạo và sự kiên Form Load như sau:
- private int _parentTop;
- private int _parentLeft;
- private int _parentWidth;
- private int _parentHeight;
-
- public FrConnection(int parentTop, int parentLeft, int parentWidth, int parrentHeight)
- {
- _parentTop = parentTop;
- _parentLeft = parentLeft;
- _parentWidth = parentWidth;
- _parentHeight = parrentHeight;
- InitializeComponent();
- }
-
- private void FrConnection_Load(object sender, EventArgs e)
- {
- Left = _parentLeft - 50;
- Top = ((_parentTop + _parentHeight / 2)) - (Height / 2);
- timer.Start();
- }
Ở sự kiện time_Tick khai báo:
- private void timer_Tick(object sender, EventArgs e)
- {
- Left += 50;
- if (Left >= ((_parentLeft + _parentWidth / 2) - Width / 2))
- {
- Left = ((_parentLeft + _parentWidth / 2)) - (Width / 2);
- Top = ((_parentTop + _parentHeight / 2)) - (Height / 2);
- timer.Stop();
- }
- }
Ở Form cha, khi open Form con sẽ cần truyền các tham số top,left, width, heigh của mình vào Form con:
- private void newToolStripMenuItem_Click(object sender, EventArgs e)
- {
- FrConnection fr = new FrConnection(this.Top, this.Left, this.Width, this.Height);
- fr.ShowDialog();
- }
Vị trí của Form con lúc bắt đầu khởi tạo:
Sau đó Form sẽ trượt ra chính giữa:
Có thể tùy chỉnh quãng đường Form sẽ trượt tại sự kiện Form Load và tốc độ trượt của Form tại sự kiện time_Tick.