如何将表单设置为最顶层

时间:2014-07-28 05:38:06

标签: c# winforms

我想要做的就是设置我的,它上面有一个图片框,成为我计算机上最顶层的对象并保持这种状态。我试过用f.topmost = true;但如果我点击某些东西,我的表格就不再是最重要的了。 我从dll运行我的表单(dll的代码在下面)。我甚至试图在我的表格中添加一个载荷,这也没有做任何事情。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace pic
{
public class Class1
{
    [DllImport("user32.dll", SetLastError = true)]
    private static extern UInt32 GetWindowLong(IntPtr hWnd, int nIndex);
    [DllImport("user32.dll")]
    static extern int SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
    [DllImport("user32.dll")]
    static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
    public const int GWL_EXSTYLE = -20;
    public const int WS_EX_LAYERED = 0x80000;
    public const int WS_EX_TRANSPARENT = 0x20;
    public const int LWA_ALPHA = 0x2;
    public const int LWA_COLORKEY = 0x1;
    Form f = new Form();

    public void t(int LocalX, int LocalY, string PicLocal, byte transparency)
    {
        f.Load += new EventHandler(ProgramViwer_Load);
        Bitmap bitmap;
       // Form f = new Form();
        f.BackColor = Color.White;
        f.FormBorderStyle = FormBorderStyle.None;
        f.Bounds = Screen.PrimaryScreen.Bounds;

        bitmap = new Bitmap(PicLocal);
        f.Size = new Size(bitmap.Size.Width, bitmap.Size.Height);
        f.StartPosition = FormStartPosition.Manual;
        f.SetDesktopLocation(LocalX, LocalY);

        Application.EnableVisualStyles();



        PictureBox PictureBox1 = new PictureBox();

        PictureBox1.Location = new System.Drawing.Point(0, 0);
        PictureBox1.Image = bitmap;

        PictureBox1.Size = new System.Drawing.Size(bitmap.Size.Width, bitmap.Size.Height);

        PictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;

        f.Controls.Add(PictureBox1);

        f.AllowTransparency = true;
        SetWindowLong(f.Handle, GWL_EXSTYLE,
        (IntPtr)(GetWindowLong(f.Handle, GWL_EXSTYLE) | WS_EX_LAYERED | WS_EX_TRANSPARENT));
        // set transparency to 50% (128)
        SetLayeredWindowAttributes(f.Handle, 0, transparency, LWA_ALPHA);

        Color BackColor = Color.White;
        f.TransparencyKey = BackColor;
        f.Opacity = transparency / 255f;

        Application.Run(f);

    }

    private void ProgramViwer_Load(object sender, EventArgs e)
    {
        f.TopMost = true;
    }

}
}

1 个答案:

答案 0 :(得分:0)

您的问题是其他窗口也将其“TopMost”属性设置为true。这不是最干净的解决方案,但应该有效。

new Thread(() =>
                {
                    try
                    {
                        while (true)
                        {
                            this.TopMost = true;
                            Thread.Sleep(1);
                        }
                    }
                    catch (Exception ex) { }
                }).Start();