zoukankan      html  css  js  c++  java
  • C#传递自定义结构体

    利用WINDOWS消息循环的机制传递自定义的结构体在编程的过程中可能经常会用到,在这里我就编写了一个简单的结构体的传递代码,需要注意的是类是不能够传递的,能进行传递的只能是结构体

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

    namespace CustomTest
    {
        public struct Student
        {
            public string name ;
            public string id;
        }

        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private const int WM_USERMSG = 0x0400 + 1;

            [DllImport("User32.dll", EntryPoint = "SendMessage")]

            private static extern int SendMessage(

                   IntPtr hWnd,   // handle to destination window

                   int Msg,    // message

                   int wParam, // first message parameter

                   IntPtr lParam // second message parameter

             );


            protected override void DefWndProc(ref Message m)
            {
                switch (m.Msg)
                {
                    case WM_USERMSG:
                        Student s = (Student)Marshal.PtrToStructure(m.LParam, typeof(Student));
                        MessageBox.Show(s.name, s.id);
                        break;

                }
                base.DefWndProc(ref m);
            }

            private void button1_Click(object sender, EventArgs e)
            {
                Student s = new Student();
                s.name = "zhouweigang";
                s.id = "11103132";
                IntPtr handle = IntPtr.Zero;
                handle = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Student)));
                Marshal.StructureToPtr(s, handle, true);

                if (handle != IntPtr.Zero)
                {
                    SendMessage(this.Handle, WM_USERMSG, 0, handle);
                }
            }

        }
    }

  • 相关阅读:
    Triangle
    Remove Duplicate Letters
    array 并不会被默认初始化
    Unique Binary Search Trees
    有些障碍的 unique path
    unique paths
    最长增长序列的长度(LIS)
    极其简单的复数类,只是不想再推演一遍复数四则运算
    安卓_11
    安卓_10
  • 原文地址:https://www.cnblogs.com/zhangpengshou/p/1699853.html
Copyright © 2011-2022 走看看