Ubuntu22.04 Mono C# gtk 编程习练笔记(三)

Mono对gtk做了很努力的封装,即便如此仍然与System.Windows.Form中的控件操作方法有许多差异,这是gtk本身特性或称为特色决定的。下面是gtk常用控件在Mono C#中的一些用法。

Button控件

在工具箱中该控件的clicked信号双击后自动生成回调函数prototype,下面的函数当Button12点击后其标签名变为"Button12 is Pressed!"。还有ToggleButton,ImageButton 用法类似。

    protected void OnButton12Clicked(object sender, EventArgs e)
    {
        Button12.Label = "Button12 is Pressed!";
    }

Entry控件

用法与Winform的TextBox非常相似。

    protected void OnButton13Clicked(object sender, EventArgs e)
    {
        string sText = "";
        entry2.Text = "Hello";
        sText = entry2.Text;
    }

Checkbutton和Radiobutton

读:当选中后,它的Active属性是true ; 未选中时,它的Active属性是false。

写:Checkbutton1.Active = true; Radiobutton1.Active = true;

ColorButton颜料按钮

自动调出颜色选取dialog,用colorbutton1.Color.Red 读入红色值,或Gr

een/Blue读取绿色和蓝色值。因为调出的是dialog,所以用其它Button调用dialog功效是类同的。

    protected void OnColorbutton1ColorSet(object sender, EventArgs e)
    {
        var redcolor = colorbutton1.Color.Red;
        var greencolor = colorbutton1.Color.Green;
        var bluecolor = colorbutton1.Color.Blue;
    }

下面是通过 ColorSelectionDialog 方式调出颜料盒对话框,用后直接dispose扔给收垃圾的,不需要destroy打砸它。C#是通过runtime执行的,不是CLR平台管理的要自己处理垃圾,自动回收是管不了的。

   protected void OnButton3Clicked(object sender, EventArgs e)
    {
        Gtk.ColorSelectionDialog colorSelectionDialog = new Gtk.ColorSelectionDialog("Color selection dialog");
        colorSelectionDialog.ColorSelection.HasOpacityControl = true;
        colorSelectionDialog.ColorSelection.HasPalette = true;
        colorSelectionDialog.ColorSelection.CurrentColor = StoreColor;

        if (colorSelectionDialog.Run() == (int)ResponseType.Ok)
        {
            StoreColor = colorSelectionDialog.ColorSelection.CurrentColor;
            var redcolor = colorSelectionDialog.ColorSelection.CurrentColor.Red;
            var greencolor = colorSelectionDialog.ColorSelection.CurrentColor.Green;
            var bluecolor = colorSelectionDialog.ColorSelection.CurrentColor.Blue;
        }
        colorSelectionDialog.Dispose();
    }

 FontButton控件

它通过FontName返回字体名称、字型、字号,自动调用字体选择对话框。

    protected void OnFontbutton1FontSet(object sender, EventArgs e)
    {
        entry1.Text = fontbutton1.FontName;
    }

也可以使用其它钮调用字体选择对话框,用后Dispose()掉。

    protected void OnButton2Clicked(object sender, EventArgs e)
    {
        Gtk.FontSelectionDialog fontSelectionDialog = new Gtk.FontSelectionDialog("Font selection");
        if (fontSelectionDialog.Run() == (int)ResponseType.Ok)
        {
            entry1.Text = fontSelectionDialog.FontName;
        }
        fontSelectionDialog.Dispose();
    }

ComboBox框

用InsertText用AppendText添加新内容,用RemoveText方法删除指定项,用Active属性选中指定项显示在显示框中。ComboBox框类似于Winform的ListBox,是不能输入的。

    protected void OnButton7Clicked(object sender, EventArgs e)
    {
        combobox1.InsertText(0, "Item - 1");
        combobox1.InsertText(0, "Item - 2");
        combobox1.InsertText(0, "Item - 3");
        combobox1.InsertText(0, "Item - 4");
        combobox1.InsertText(0, "Item - 5");
        combobox1.InsertText(0, "Item - 6");
        combobox1.InsertText(0, "Item - 7");
        combobox1.InsertText(0, "Item - 8");
        combobox1.Active = 5;
    }

ComboBoxEntry框

ComboBoxEntry框是可输入的,用法同ComboBox。

TreeView列表

这框比较有特色,可显示图片和文本。图片用Gdk.Pixbuf装载,是个特殊类型。

    protected void OnButton15Clicked(object sender, EventArgs e)
    {
        Gtk.ListStore listStore = new Gtk.ListStore(typeof(Gdk.Pixbuf), typeof(string), typeof(string));
        treeview1.Model = null;
        treeview1.AppendColumn("Icon", new Gtk.CellRendererPixbuf(), "pixbuf", 0);
        treeview1.AppendColumn("Artist", new Gtk.CellRendererText(), "text", 1);
        treeview1.AppendColumn("Title", new Gtk.CellRendererText(), "text", 2);
        listStore.AppendValues(new Gdk.Pixbuf("sample.png"), "Rupert", "Yellow bananas");
        treeview1.Model = listStore;
        listStore.Dispose();
    }

DrawArea Cairo 图像

是做图用的,先创建surface,可以在内存中、图片上、pdf上、DrawArea上画图或写字,也可以存成png图片,图形可以变换座标。在内存中绘图,然后在DrawAre的context上show显示,或在其它地方显示。功能很灵活,与GDI在bitmap上做图,通过hdc显示在pictureBox上有对比性。

    protected void OnButton11Clicked(object sender, EventArgs e)
    {
        //
        // Creates an Image-based surface with with data stored in
        // ARGB32 format.  
        //
        drawingarea1Width = drawingarea1.Allocation.Width;
        drawingarea1Height = drawingarea1.Allocation.Height;
        ImageSurface surface = new ImageSurface(Format.ARGB32, drawingarea1Width, drawingarea1Height);

        // Create a context, "using" is used here to ensure that the
        // context is Disposed once we are done
        //
        //using (Context ctx = new Cairo.Context(surface))
        using (Context ctx = Gdk.CairoHelper.Create(drawingarea1.GdkWindow))
        {
            // Select a font to draw with
            ctx.SelectFontFace("serif", FontSlant.Normal, FontWeight.Bold);
            ctx.SetFontSize(32.0);

            // Select a color (blue)
            ctx.SetSourceRGB(0, 0, 1);
            //ctx.LineTo(new PointD(iArea1ObjX, drawingarea1.Allocation.Height));
            //ctx.StrokePreserve();

            // Draw
            ctx.MoveTo(iArea1ObjX, iArea1ObjY);
            ctx.ShowText("Hello, World");


            /*
            //Drawings can be save to png picture file
            //surface.WriteToPng("test.png");

            //Context ctxArea1 = Gdk.CairoHelper.Create(drawingarea1.GdkWindow);
            //Surface surface1 = new Cairo.ImageSurface("test.png");

            //Option: coordinator change, origin 0,0 is the middle of the drawingarea
            //ctxArea1.Translate(drawingarea1Width / 2, drawingarea1Height / 2);
            //surface.Show(ctxArea1, 0, 0);

            //ctxArea1.Dispose();
            */
        }
    }

About对话框

固定格式的对话框,有贡献者、文档人员、版权说明等,与windows的about不太相同。

    protected void OnButton9Clicked(object sender, EventArgs e)
    {
        string[] textabout = {"abcde","fdadf","adsfasdf" };
        const string LicensePath = "COPYING.txt";

        Gtk.AboutDialog aboutDialog = new Gtk.AboutDialog();
        aboutDialog.Title = "About mono learning";
        aboutDialog.Documenters = textabout;
        //aboutDialog.License = "mit license";
        aboutDialog.ProgramName = "my Program";
        aboutDialog.Logo = new Gdk.Pixbuf("logo.png");
        //aboutDialog.LogoIconName = "logo.png";
        //aboutDialog.AddButton("New-Button", 1);
        aboutDialog.Artists = textabout;
        aboutDialog.Authors = textabout;
        aboutDialog.Comments = "This is the comments";
        aboutDialog.Copyright = "The copyright";
        aboutDialog.TranslatorCredits = "translators";
        aboutDialog.Version = "1.12";
        aboutDialog.WrapLicense = true;
        aboutDialog.Website = "www.me.com";
        aboutDialog.WebsiteLabel = "A website";
        aboutDialog.WindowPosition = WindowPosition.Mouse;
        try
        {
            aboutDialog.License = System.IO.File.ReadAllText(LicensePath);
        }
        catch (System.IO.FileNotFoundException)
        {
            aboutDialog.License = "Could not load license file '" + LicensePath + "'.\nGo to http://www.abcd.org";
        }
        aboutDialog.Run();
        aboutDialog.Destroy();
        aboutDialog.Dispose();
    }

Timer时钟

使用Glib的时钟,100ms

timerID1 = GLib.Timeout.Add(100, OnTimedEvent1);

使用System的时钟,300ms

 aTimer = new System.Timers.Timer(300);
 aTimer.Elapsed += OnTimedEvent;
 aTimer.AutoReset = true;
 aTimer.Enabled = true;

异步写文件(VB.NET)

    protected void OnButton4Clicked(object sender, EventArgs e)
    {
        Task r = Writedata();

        async Task Writedata()
        {
            await Task.Run(() =>
            {
                VB.FileSystem.FileOpen(1, "VBNETTEST.TXT", VB.OpenMode.Output, VB.OpenAccess.Write, VB.OpenShare.Shared);
                VB.FileSystem.WriteLine(1, "Hello World! - 1");
                VB.FileSystem.WriteLine(1, "Hello World! - 2");
                VB.FileSystem.WriteLine(1, "Hello World! - 3");
                VB.FileSystem.WriteLine(1, "Hello World! - 4");
                VB.FileSystem.WriteLine(1, "Hello World! - 5");
                VB.FileSystem.FileClose(1);
                return 0;
            });
        }
    }

SQLite操作

创建Table

    protected void OnButton13Clicked(object sender, EventArgs e)
    {
        const string connectionString = "URI=file:SqliteTest.db, version=3";
        IDbConnection dbcon = new SqliteConnection(connectionString);
        dbcon.Open();
        IDbCommand dbcmd = dbcon.CreateCommand();
        string sql;
            sql =
                 "CREATE TABLE employee (" +
                 "firstname nvarchar(32)," +
                 "lastname nvarchar(32))";
            dbcmd.CommandText = sql;
            dbcmd.ExecuteNonQuery();

            dbcmd.Dispose();
            dbcon.Close();
    }

INSERT记录

    protected void OnButton13Clicked(object sender, EventArgs e)
    {
        const string connectionString = "URI=file:SqliteTest.db, version=3";
        IDbConnection dbcon = new SqliteConnection(connectionString);
        dbcon.Open();
        IDbCommand dbcmd = dbcon.CreateCommand();
        string sql;
            sql =
                 "INSERT INTO employee(" +
                 "firstname, lastname)" +
                 "values('W1ang', 'B1odang')";
            dbcmd.CommandText = sql;
            dbcmd.ExecuteNonQuery();

            dbcmd.Dispose();
            dbcon.Close();
    }

循环读

    protected void OnButton13Clicked(object sender, EventArgs e)
    {
        const string connectionString = "URI=file:SqliteTest.db, version=3";
        IDbConnection dbcon = new SqliteConnection(connectionString);
        dbcon.Open();
        IDbCommand dbcmd = dbcon.CreateCommand();
        string sql;
            sql =
               "SELECT firstname, lastname " +
               "FROM employee";
            dbcmd.CommandText = sql;
            IDataReader reader = dbcmd.ExecuteReader();
            while (reader.Read())
            {
                string firstName = reader.GetString(0);
                string lastName = reader.GetString(1);
                Console.WriteLine("Name: {0} {1}",
                    firstName, lastName);
            }
            // clean up
            reader.Dispose();
            dbcmd.Dispose();
            dbcon.Close();
    }

包/项目/程序集

测试引用Windows.Form并创建了窗体和对话框,也能显示,但不是Linux平台原生的,不太美观且速度不理想。如果只是创建了不Show,让它处于Hide状态,比如带sort属性的ListBox,还是可以使用的。

Mono自己有许多基础库

还有DOTNET的库

还有其它第三方库

  • 32
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值