view/MainForm.cs....

本文介绍了一个股票交易系统的实现细节,包括主窗口的功能布局与交互逻辑,以及交易对话框的设计。系统能够从网络获取股票的最新价格和名称,并通过SQL查询展示交易记录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//========MainForm.cs==========================================================

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace portfolio.View
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string inSql = @"select '1' as id, code,
                                min(tradedate) as tradedate ,
                                (sum(sumc)/sum(tradecount)) as price,
                                sum(tradecount) as countt,sum(sumc) as sumcc
                            from (select *, (price * tradecount) as sumc from tradebase ) as view1
                            where direct ='in'
                            group by code  ";

            string outSqlFormat = @"select min(tradedate) as tradedate ,
                                (sum(sumc)/sum(tradecount)) as price,
                                sum(tradecount) as countt,sum(sumc) as sumcc
                            from (select *, (price * tradecount) as sumc from tradebase ) as view1
                            where code = '{0}' and direct ='out'";

            DataSet ds = Global.AccessDB.SelectToDataSet(inSql);
            DataTable dt = ds.Tables[0];

            //ID,direct,
            //code,[name_name]
            //tradeDate,price,tradecount,sum
            //[currentPrice_curPrice]
            //[tradeDate_outdate,price_outprice,count_outcount,sum_outsum]
            //

            dt.Columns.Add("name");//from web
            dt.Columns.Add("currentPrice");//from web

            dt.Columns.Add("outdate");
            dt.Columns.Add("outprice");
            dt.Columns.Add("outcount");
            dt.Columns.Add("outsum");

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string id,code,name,price;
                id = dt.Rows[i]["ID"].ToString();
              
                code = dt.Rows[i]["code"].ToString();
                this.GetNameAndPrice(code,out  name, out price);
                dt.Rows[i]["name"] = name;
                dt.Rows[i]["currentPrice"] = price;

                outSqlFormat = string.Format(outSqlFormat, code);
                DataSet outDS = Global.AccessDB.SelectToDataSet(outSqlFormat);

                if (outDS == null || outDS.Tables.Count == 0 || outDS.Tables[0].Rows.Count == 0) continue;

                dt.Rows[i]["outdate"] = outDS.Tables[0].Rows[0]["tradedate"].ToString();
                dt.Rows[i]["outprice"] = outDS.Tables[0].Rows[0]["price"].ToString();
                dt.Rows[i]["outcount"] = outDS.Tables[0].Rows[0]["countt"].ToString();
                dt.Rows[i]["outsum"] = outDS.Tables[0].Rows[0]["sumcc"].ToString();
               
            }
            this.dataGridView1.DataSource = ds.Tables[0].DefaultView;


        }


        public void GetNameAndPrice(string code, out string name, out string price)
        {
            name = price = "";
            try
            {
                string url = @"http://www.google.com.hk/finance?q=SHE:{0}&gl=cn";
                url = string.Format(url, code);

                System.Net.WebRequest req = WebRequest.Create(url);

                WebResponse rep = req.GetResponse();

                Stream webstream = rep.GetResponseStream();


                StreamReader sr = new StreamReader(webstream, Encoding.UTF8  );

                string br = sr.ReadToEnd();
               
                //<title>????: SHE:000707 ????? - Google ??</title>
                int b, e;
                b = br.IndexOf("<title>") + "<title>".Length;
                e = br.IndexOf("</title>");
                string tg = br.Substring(b, e - b);
                b = tg.IndexOf(": SHE:");
                if (b < 0) b = tg.IndexOf(": SHA:");
                name = tg.Substring(0, b);

                string ft = "<span id=/"ref_"; //701778_l">19.29
                b = br.IndexOf(ft) + ft.Length + "701778_l/">".Length;
                br = br.Substring(b);
                e = br.IndexOf("</span>");
                price = br.Substring(0, e);
            }
            catch
            {
            }

        }


        private void MainForm_Load(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            TradeForm tf = new TradeForm();
            tf.main = this;
            tf.ShowDialog();
        }
    }
}

//====MainForm.Designer.cs===========================================================

namespace portfolio.View
{
    partial class MainForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.dataGridView1 = new System.Windows.Forms.DataGridView();
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.ID = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.Code = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.name = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.currentPrice = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.bookInterest = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.TradeDate = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.Price = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.Count = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.Sum = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.outdate = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.outprice = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.outcount = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.outsum = new System.Windows.Forms.DataGridViewTextBoxColumn();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
            this.SuspendLayout();
            //
            // dataGridView1
            //
            this.dataGridView1.AllowUserToAddRows = false;
            this.dataGridView1.AllowUserToDeleteRows = false;
            this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.ID,
            this.Code,
            this.name,
            this.currentPrice,
            this.bookInterest,
            this.TradeDate,
            this.Price,
            this.Count,
            this.Sum,
            this.outdate,
            this.outprice,
            this.outcount,
            this.outsum});
            this.dataGridView1.Location = new System.Drawing.Point(1, 51);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.ReadOnly = true;
            this.dataGridView1.Size = new System.Drawing.Size(708, 384);
            this.dataGridView1.TabIndex = 0;
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(12, 12);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 1;
            this.button1.Text = "Refresh";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // button2
            //
            this.button2.Location = new System.Drawing.Point(110, 12);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 23);
            this.button2.TabIndex = 2;
            this.button2.Text = "交易";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            //
            // ID
            //
            this.ID.DataPropertyName = "ID";
            this.ID.HeaderText = "ID";
            this.ID.Name = "ID";
            this.ID.ReadOnly = true;
            this.ID.Visible = false;
            //
            // Code
            //
            this.Code.DataPropertyName = "Code";
            this.Code.HeaderText = "代码";
            this.Code.Name = "Code";
            this.Code.ReadOnly = true;
            //
            // name
            //
            this.name.DataPropertyName = "name";
            this.name.HeaderText = "证券名称";
            this.name.Name = "name";
            this.name.ReadOnly = true;
            //
            // currentPrice
            //
            this.currentPrice.DataPropertyName = "currentPrice";
            this.currentPrice.HeaderText = "当前价格";
            this.currentPrice.Name = "currentPrice";
            this.currentPrice.ReadOnly = true;
            //
            // bookInterest
            //
            this.bookInterest.DataPropertyName = "bookInterest";
            this.bookInterest.HeaderText = "盈亏";
            this.bookInterest.Name = "bookInterest";
            this.bookInterest.ReadOnly = true;
            //
            // TradeDate
            //
            this.TradeDate.DataPropertyName = "TradeDate";
            this.TradeDate.HeaderText = "买入日期";
            this.TradeDate.Name = "TradeDate";
            this.TradeDate.ReadOnly = true;
            //
            // Price
            //
            this.Price.DataPropertyName = "Price";
            this.Price.HeaderText = "买入价格";
            this.Price.Name = "Price";
            this.Price.ReadOnly = true;
            //
            // Count
            //
            this.Count.DataPropertyName = "Countt";
            this.Count.HeaderText = "买入数量";
            this.Count.Name = "Count";
            this.Count.ReadOnly = true;
            //
            // Sum
            //
            this.Sum.DataPropertyName = "sumcc";
            this.Sum.HeaderText = "买入成本";
            this.Sum.Name = "Sum";
            this.Sum.ReadOnly = true;
            //
            // outdate
            //
            this.outdate.DataPropertyName = "outdate";
            this.outdate.HeaderText = "卖出日期";
            this.outdate.Name = "outdate";
            this.outdate.ReadOnly = true;
            //
            // outprice
            //
            this.outprice.DataPropertyName = "outprice";
            this.outprice.HeaderText = "卖出价格";
            this.outprice.Name = "outprice";
            this.outprice.ReadOnly = true;
            //
            // outcount
            //
            this.outcount.DataPropertyName = "outcount";
            this.outcount.HeaderText = "卖出数量";
            this.outcount.Name = "outcount";
            this.outcount.ReadOnly = true;
            //
            // outsum
            //
            this.outsum.DataPropertyName = "outsum";
            this.outsum.HeaderText = "卖出总价";
            this.outsum.Name = "outsum";
            this.outsum.ReadOnly = true;
            //
            // MainForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(709, 437);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.dataGridView1);
            this.Name = "MainForm";
            this.Text = "MainForm";
            this.Load += new System.EventHandler(this.MainForm_Load);
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.DataGridView dataGridView1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.DataGridViewTextBoxColumn ID;
        private System.Windows.Forms.DataGridViewTextBoxColumn Code;
        private System.Windows.Forms.DataGridViewTextBoxColumn name;
        private System.Windows.Forms.DataGridViewTextBoxColumn currentPrice;
        private System.Windows.Forms.DataGridViewTextBoxColumn bookInterest;
        private System.Windows.Forms.DataGridViewTextBoxColumn TradeDate;
        private System.Windows.Forms.DataGridViewTextBoxColumn Price;
        private System.Windows.Forms.DataGridViewTextBoxColumn Count;
        private System.Windows.Forms.DataGridViewTextBoxColumn Sum;
        private System.Windows.Forms.DataGridViewTextBoxColumn outdate;
        private System.Windows.Forms.DataGridViewTextBoxColumn outprice;
        private System.Windows.Forms.DataGridViewTextBoxColumn outcount;
        private System.Windows.Forms.DataGridViewTextBoxColumn outsum;
    }
}

 

//======TradeForm.cs===================================================================

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace portfolio.View
{
    public partial class TradeForm : Form
    {
        public MainForm main;
        public string pid="";

        public TradeForm()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if(this.txbCode .Text .Trim ().Length != 6) return ;

            if (main != null)
            {
                string name, price;
                main.GetNameAndPrice(this.txbCode.Text.Trim(), out name, out price);
                this.txbName.Text = name;
                this.txbPrice.Text = price;

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if ( 1==0 && (this.txbCode.Text.Trim().Length == 0 ||
                this.txbCount.Text.Trim().Length == 0 ||
                //this.txbName.Text.Trim().Length == 0 ||
                this.txbPrice.Text.Trim().Length == 0 ||
                this.cmbDirect.Text.Trim().Length == 0))
            {
                MessageBox.Show("输入不完全!");
            }
            else
            {
                string sql = @"insert into tradebase (id,code,tradedate,direct,price,tradecount,fee) values ('{0}','{1}','{2}','{3}',{4},{5},{6})";

                string id, code, tradedate, direct, price, count, fee;
                id = pid + System.Guid.NewGuid().ToString();
                code = this.txbCode.Text.Trim();
                tradedate = this.txbDate.Value.ToShortDateString();
                direct = this.cmbDirect.Text.Trim();
                if (direct == "买")
                {
                    direct = "in";
                }
                else
                {
                    direct = "out";
                }
                price = this.txbPrice.Text.Trim();
                count = this.txbCount.Text.Trim();
                fee = "0";//TODO

                sql = string.Format(sql, id, code, tradedate, direct, price, count, fee);

                bool r=  Global.AccessDB.ExecuteSQLNonquery(sql );
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
    }
}
//========TradeForm.Designer.cs==========================================================

namespace portfolio.View
{
    partial class TradeForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.cmbDirect = new System.Windows.Forms.ComboBox();
            this.label1 = new System.Windows.Forms.Label();
            this.txbCode = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.txbCount = new System.Windows.Forms.TextBox();
            this.txbPrice = new System.Windows.Forms.TextBox();
            this.txbName = new System.Windows.Forms.TextBox();
            this.label6 = new System.Windows.Forms.Label();
            this.button2 = new System.Windows.Forms.Button();
            this.txbDate = new System.Windows.Forms.DateTimePicker();
            this.SuspendLayout();
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(92, 165);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "确定";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // cmbDirect
            //
            this.cmbDirect.FormattingEnabled = true;
            this.cmbDirect.Items.AddRange(new object[] {
            "买",
            "卖"});
            this.cmbDirect.Location = new System.Drawing.Point(87, 122);
            this.cmbDirect.Name = "cmbDirect";
            this.cmbDirect.Size = new System.Drawing.Size(100, 21);
            this.cmbDirect.TabIndex = 1;
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(215, 20);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(31, 13);
            this.label1.TabIndex = 2;
            this.label1.Text = "名称";
            //
            // txbCode
            //
            this.txbCode.Location = new System.Drawing.Point(87, 17);
            this.txbCode.Name = "txbCode";
            this.txbCode.Size = new System.Drawing.Size(122, 20);
            this.txbCode.TabIndex = 3;
            this.txbCode.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(50, 73);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(31, 13);
            this.label2.TabIndex = 4;
            this.label2.Text = "现价";
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(50, 101);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(31, 13);
            this.label3.TabIndex = 5;
            this.label3.Text = "数量";
            //
            // label4
            //
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(50, 21);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(31, 13);
            this.label4.TabIndex = 6;
            this.label4.Text = "代码";
            //
            // label5
            //
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(26, 125);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(55, 13);
            this.label5.TabIndex = 7;
            this.label5.Text = "买卖方向";
            //
            // txbCount
            //
            this.txbCount.Location = new System.Drawing.Point(87, 95);
            this.txbCount.Name = "txbCount";
            this.txbCount.Size = new System.Drawing.Size(100, 20);
            this.txbCount.TabIndex = 8;
            //
            // txbPrice
            //
            this.txbPrice.Location = new System.Drawing.Point(87, 69);
            this.txbPrice.Name = "txbPrice";
            this.txbPrice.Size = new System.Drawing.Size(100, 20);
            this.txbPrice.TabIndex = 9;
            //
            // txbName
            //
            this.txbName.Location = new System.Drawing.Point(252, 16);
            this.txbName.Name = "txbName";
            this.txbName.Size = new System.Drawing.Size(100, 20);
            this.txbName.TabIndex = 10;
            //
            // label6
            //
            this.label6.AutoSize = true;
            this.label6.Location = new System.Drawing.Point(26, 47);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(55, 13);
            this.label6.TabIndex = 11;
            this.label6.Text = "交易日期";
            //
            // button2
            //
            this.button2.Location = new System.Drawing.Point(191, 165);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 23);
            this.button2.TabIndex = 13;
            this.button2.Text = "返回";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            //
            // txbDate
            //
            this.txbDate.Location = new System.Drawing.Point(87, 43);
            this.txbDate.Name = "txbDate";
            this.txbDate.Size = new System.Drawing.Size(265, 20);
            this.txbDate.TabIndex = 15;
            //
            // TradeForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(380, 239);
            this.Controls.Add(this.txbDate);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.label6);
            this.Controls.Add(this.txbName);
            this.Controls.Add(this.txbPrice);
            this.Controls.Add(this.txbCount);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.txbCode);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.cmbDirect);
            this.Controls.Add(this.button1);
            this.Name = "TradeForm";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "TradeForm";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.ComboBox cmbDirect;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox txbCode;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.TextBox txbCount;
        private System.Windows.Forms.TextBox txbPrice;
        private System.Windows.Forms.TextBox txbName;
        private System.Windows.Forms.Label label6;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.DateTimePicker txbDate;
    }
}

using System; using System.Drawing; using System.Windows.Forms; using Thorlabs.TLBP2.Interop; namespace BeamProfilePlotter { public partial class MainForm : Form { private TLBP2 _device; private PictureBox _profilePictureBox; private Button _captureButton; public MainForm() { InitializeComponent(); SetupUI(); InitializeDevice(); } private void SetupUI() { _profilePictureBox = new PictureBox { Dock = DockStyle.Fill }; _captureButton = new Button { Text = "Capture Beam", Dock = DockStyle.Bottom }; _captureButton.Click += CaptureButton_Click; Controls.Add(_profilePictureBox); Controls.Add(_captureButton); } private void InitializeDevice() { try { // 替换为实际设备资源名(如 USB 或 ASRL 地址) _device = new TLBP2("USB0::0x1313::0x80B8::M12345678::INSTR", true, true); } catch (Exception ex) { MessageBox.Show($"Device init failed: {ex.Message}"); } } private void CaptureButton_Click(object sender, EventArgs e) { try { // 1. 获取狭缝配置 byte[] slitUsed = new byte[4]; byte[] slitLength = new byte[4]; byte[] slitWidth = new byte[4]; byte[] slitOrientation = new byte[4]; _device.get_slit_parameter(slitUsed, slitLength, slitWidth, slitOrientation); // 2. 查找 X/Y 方向的有效狭缝 int xSlit = -1, ySlit = -1; for (int i = 0; i < 4; i++) { if (slitUsed[i] == 1) { if (slitOrientation[i] == 0) xSlit = i; // 0 = X方向 if (slitOrientation[i] == 1) ySlit = i; // 1 = Y方向 } } if (xSlit == -1 || ySlit == -1) throw new Exception("Valid X/Y slits not found"); // 3. 获取扫描数据 double power; float saturation; double[] powerData = new double[2128]; // 功率窗数据 _device.request_scan_data(out power, out saturation, powerData); // 4. 获取 X 方向数据 ushort xSamples; float xDarkLevel; _device.get_scan_data_information((byte)xSlit, out xSamples, out xDarkLevel); double[] xIntensities = new double[xSamples]; double[] xPositions = new double[xSamples]; _device.get_sample_intensities((byte)xSlit, xIntensities, xPositions); // 5. 获取 Y 方向数据 ushort ySamples; float yDarkLevel; _device.get_scan_data_information((byte)ySlit, out ySamples, out yDarkLevel); double[] yIntensities = new double[ySamples]; double[] yPositions = new double[ySamples]; _device.get_sample_intensities((byte)ySlit, yIntensities, yPositions); // 6. 重建二维光斑图像 Bitmap profileImage = ReconstructBeamProfile(xIntensities, yIntensities); _profilePictureBox.Image = profileImage; } catch (Exception ex) { MessageBox.Show($"Error: {ex.Message}"); } } private Bitmap ReconstructBeamProfile(double[] xData, double[] yData) { int width = xData.Length; int height = yData.Length; Bitmap bmp = new Bitmap(width, height); // 归一化数据 double xMax = GetMaxValue(xData); double yMax = GetMaxValue(yData); // 重建算法:假设高斯分布 (I(x,y) = I_x(x) * I_y(y)) for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { double intensity = (xData[x] / xMax) * (yData[y] / yMax); int rgbValue = (int)(intensity * 255); rgbValue = Math.Clamp(rgbValue, 0, 255); bmp.SetPixel(x, y, Color.FromArgb(rgbValue, rgbValue, rgbValue)); } } return bmp; } private double GetMaxValue(double[] data) { double max = double.MinValue; foreach (var val in data) if (val > max) max = val; return max; } protected override void OnFormClosing(FormClosingEventArgs e) { _device?.Dispose(); base.OnFormClosing(e); } } }如何用c# WPF MVVM模式重写以上代码
06-11
WPF 登陆后(其中UserDepartment是从登陆页面的BtnLogin_Click获取到的)进入主页面MonitorWindow后,ucTWSTK如何从MonitorWindow获取到UserDepartment,请给出代码 请详细在每个部分给出代码 MonitorWindow的XAML代码如下 <Window x:Class="Monitor.View.MonitorWindow" xmlns:local="clr-namespace:Monitor.View" xmlns:uc="clr-namespace:Monitor" d:DataContext="{d:DesignInstance Type=uc:MonitorWindowViewModel}" mc:Ignorable="d" Name="MainWindow" Title="" Height="Auto" Width="Auto" WindowStartupLocation="CenterScreen" WindowState="Maximized" Unloaded="MainWindow_Unloaded" Loaded="MainWindow_Loaded"> <DockPanel> <Expander ExpandDirection="Left" Background="White" DockPanel.Dock="Right" IsExpanded="True"> <ScrollViewer Margin="0" VerticalScrollBarVisibility="Auto"> <WrapPanel FlowDirection="LeftToRight" Orientation="Vertical" Name="ddd" ScrollViewer.VerticalScrollBarVisibility="Auto"> <uc:ucsCtrl Width="270" Height="auto" Margin="4,1,1,1" x:Name="uiSTCsCtrl"></uc:ucsCtrl> </WrapPanel> </ScrollViewer> </Expander> </DockPanel> </Window> MonitorWindow里面ucsCtrl的XAML代码如下 <UserControl x:Class="Monitor.ucsCtrl" mc:Ignorable="d" d:DesignHeight="270" d:DesignWidth="270"> <GroupBox Header="STCs Infomations."> <GroupBox.HeaderTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <materialDesign:PackIcon Kind="SquareRoundedOutline" Height="16" Width="16" VerticalAlignment="Center" /> <TextBlock FontSize="12" Padding="0" VerticalAlignment="Center" Style="{StaticResource MaterialDesignSubtitle1TextBlock}" Text="{Binding}" /> </StackPanel> </DataTemplate> </GroupBox.HeaderTemplate> <Grid Name="Grid_2" Background="Gray" Margin="-8" > <Grid.ColumnDefinitions> <ColumnDefinition Width="270"></ColumnDefinition> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="40"></RowDefinition> <RowDefinition Height="*"></RowDefinition> </Grid.RowDefinitions> <StackPanel Grid.Row="0" Orientation="Horizontal" /> <TextBox Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center" Text="St." TextAlignment="Center" IsReadOnly="True"/> <StackPanel Grid.Row="1" Name="spSTCs" Orientation="Vertical" /> </Grid> </GroupBox> </UserControl> ucsCtrl里面spSTCs的XAML代码如下 <UserControl x:Class="Monitor.ucTWSTK" mc:Ignorable="d" Height="36" Width="270"> <materialDesign:Card Margin="0,0,-71,-35" > <Grid Background="LightGray" x:Name="gdSTKGrp" Margin="0,0,70,45"> <Grid.ColumnDefinitions> <ColumnDefinition Width="70"></ColumnDefinition> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="30"></RowDefinition> </Grid.RowDefinitions> <TextBox Name="STName" Grid.Column="0" Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Center" TextAlignment="Center" IsReadOnly="True" MouseDoubleClick="ui_p_MouseDoubleClick"></TextBox> <Border Grid.Column="1" BorderBrush="DarkGray" BorderThickness="1" CornerRadius="1"> <local:ucGridStatus x:Name="ucGridStatus" BorderThickness="1" BorderBrush="LightGray"/> </Border> <TextBox Name="Ra" Grid.Column="2" Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Center" Text="0" TextAlignment="Center" IsReadOnly="True"></TextBox> </Grid> </materialDesign:Card> </UserControl> private void BtnLogin_Click(object sender, RoutedEventArgs e) { string username = txtusername.Text; string password = txtPassword.Password; string filter = $"sAMAccountName={username}"; try { if (m.IsHostChannelReadyAsync(DateTime.UtcNow.AddSeconds(1))) { using (DirectoryEntry entry = new DirectoryEntry(ldapUrl, username, password)) { object nativeObject = entry.NativeObject; DirectorySearcher searcher = new DirectorySearcher(entry); searcher.Filter = filter; SearchResult result = searcher.FindOne(); byte[] thumbnailPhoto = result.Properties["thumbnailPhoto"][0] as byte[]; string adNumber = result.Properties["description"][0] as string; msgUsers objInfo = m.GetUserInfos(adNumber); string departmentFullName = result.Properties["department"][0] as string; string department=departmentFullName.Substring(0, departmentFullName.LastIndexOf(' ') + 1).TrimEnd(); if (result == null) { System.Windows.MessageBox.Show("用户名或密码错误!"); } else { if (objInfo.Users.Count < 1) { System.Windows.MessageBox.Show("找不到账号,请联系管理员!"); } else { MonitorWindow mainForm = new MonitorWindow() { UserDepartment = department }; this.Hide(); mainForm.Show(); } } } } } catch (Exception ex) { System.Windows.MessageBox.Show($"登录失败:{ex.Message}"); } } MonitorWindow的部分函数 public MonitorWindow() { InitializeComponent(); // read configuration string sHostIP = ConfigurationManager.AppSettings["HostIP"].ToString(); string sHostPort = ConfigurationManager.AppSettings["HostPort"].ToString(); string sVer = ConfigurationManager.AppSettings["Ver"].ToString(); DataContext = new AViewModel(sHostIP, sHostPort, m_UID) { RetrieveMCSInfoInterval = ClaTool._INTERVAL_SEC_10, AppVer = sVer }; Loaded += MainWindow_Loaded; } private void MainWindow_Loaded(object sender, RoutedEventArgs e) { AdjustBtnRealtimeBasedOnDepartment(); } private void AdjustBtnRealtimeBasedOnDepartment() { if (!string.IsNullOrEmpty(UserDepartment)) { if (UserDepartment == "223") { .. uiSTCsCtrl.AdjustControlsBasedOnDepartment(UserDepartment); } else { .. } } } ucsCtrl动态生成spSTCs的函数 public partial class ucsCtrl : UserControl { private DispatcherTimer _t = new DispatcherTimer(); public ucsCtrl() { InitializeComponent(); } public void init_STCs(RepeatedField<msgF> pstcList) { spSTCs.Children.Clear(); var lstAlSTKID = (from x in pstcList select x); foreach (var m in lstAlSTKID.OrderBy(m => m.ID)) { ucTWSTK objstc = new ucTWSTK(); objstc.CURRENTCNT = m.CARRIERCNT.ToString(); spSTCs.Children.Add(objstc); } } } ucTWSTK的部分代码如下 public ucTWSTK() { InitializeComponent(); Loaded += Window_Loaded; } private void Window_Loaded(object sender, RoutedEventArgs e) { if (UserDepartment == "223") { STName.MouseDoubleClick -= ui_p_MouseDoubleClick; } }
最新发布
06-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值