当前位置:网站首页>C nanui related function integration
C nanui related function integration
2022-07-26 14:38:00 【Xiongsiyu】
Catalog
NanUI 0.88 edition Remove the startup interface ( Mask )
NanUI 0.88 edition Read local resources and embedded resources
NanUI 0.77 edition Open console
NanUI 0.77 edition C# Call multiple parameter JS Method
NanUI 0.77 edition Passing array parameters
NanUI 0.77 edition Set the full screen display of the form ( similar Kiosk Pattern )
NanUI 0.77 edition Bootstrap class API
NanUI 0.88 edition Remove the startup interface ( Mask )
The startup interface is the one that the author shows us the company's products Logo With , If you don't need it, you can remove , But you have to change the source code , If you don't want to change the source code , Directly set the background of the startup interface to white :
Mask.BackColor = Color.White;Of course, you can also set the color at will :
var mainColor = ColorTranslator.FromHtml("#E83B90");
Mask.BackColor = mainColor;The following is the official setting startup interface demo Code :
private void CustomizeMaskPanel()
{
var label = new Label
{
Text = "WinFormium\nExample Application\nPowered by NanUI",
AutoSize = false,
TextAlign = ContentAlignment.MiddleCenter,
Anchor = AnchorStyles.None,
ForeColor = Color.White,
Font = new Font("Segoe UI Light", 24.0f, GraphicsUnit.Point)
};
label.Width = Width;
label.Height = Height / 2;
label.Location = new Point(0, (Height - label.Height) / 2);
var loaderGif = new PictureBox
{
Anchor = AnchorStyles.Right | AnchorStyles.Bottom,
Size = new Size(40, 40),
Image = Properties.Resources.Indicator,
SizeMode = PictureBoxSizeMode.CenterImage
};
loaderGif.Location = new Point(Width - (int)(loaderGif.Width * 2.0f), Height - (int)(loaderGif.Height * 1.5f));
// Mask
Mask.Content.Add(label);
// Picture mask
Mask.Content.Add(loaderGif);
Mask.Image = null;
}How to build 0.88 Version source code see my post :Winform NanUI 0.88 edition Use the official source code to build the original ecological development environment Address :Winform NanUI 0.88 edition Use the official source code to build the original ecological development environment _ Xiong Siyu's blog -CSDN Blog
open NetDimension.NanUI assembly Resources.Designer.cs, You can see the local resources of the startup interface
/// <summary>
/// lookup System.Drawing.Bitmap Localized resources of type .
/// </summary>
internal static System.Drawing.Bitmap Powered {
get {
object obj = ResourceManager.GetObject("Powered", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}The removal method is also very simple , stay Formium.cs Find this field in :
internal protected ViewMask Mask { get; private set; }Put all its related references , All notes .
Click on the run , Everything is all right , Remove the startup interface , It's faster to open web pages !
NanUI 0.88 edition Read local resources and embedded resources
One 、 Import plug-ins
Before using , install NanUI Related to the plug-in , Otherwise, the project will report an error

Two 、 Read embedded resources
Add the following code to the startup class , Here you can choose to read local resources , Or embedded resources ,
As an example , I use embedded resources here
I haven't posted the complete code for some functions of the following code , If you copy it directly , There will be some errors , Deleting or changing the error reporting part by yourself is
using NetDimension.NanUI;
using NetDimension.NanUI.EmbeddedFileResource;
using NetDimension.NanUI.LocalFileResource;
using NetDimension.NanUI.ZippedResource;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Utils;
using Xilium.CefGlue;
namespace NanUIFramework
{
static class Program
{
public static MainIndex MainIndexs = null;
public static NetDimension.NanUI.HostWindow.HostWindowType HostWindowType = NetDimension.NanUI.HostWindow.HostWindowType.System;
/// <summary>
/// The main entry point for the application .
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Init();
WinFormium.CreateRuntimeBuilder(env =>
{
env.CustomCefSettings(settings =>
{
// Set... Here CEF Related parameters of
});
env.CustomCefCommandLineArguments(commandLine =>
{
// Specify here CEF Command line arguments
commandLine.AppendSwitch("disable-pinch");
});
}, app =>
{
// If you want to run only one instance , Please use this setting
app.UseSingleInstance(() =>
{
MessageBox.Show(" The instance is already running , Only one instance can run ", "Single Instance", MessageBoxButtons.OK, MessageBoxIcon.Warning);
});
// Clear all cache files , Such as cookie, history , Local storage, etc .
app.ClearCacheFile();
// Embedded resources
app.UseEmbeddedFileResource("http", "Load.Resource.Html", "View");
// Read local resources register LocalFileResource The handler , It can handle file resources in local folders .
//app.UseLocalFileResource("http", "Load.Local.Html", System.IO.Path.Combine(Application.StartupPath, "View"));
// Read ZIP resources
//app.UseZippedResource("http", "archive.app.local", Application.StartupPath + "\\View\\index.zip");
// Instantiation interface
MainIndexs = new MainIndex();
// Specifies the startup form
app.UseMainWindow(context => MainIndexs);
})
.Build()
.Run();
}
private static void Init()
{
// Initialize configuration file
ConfigManager.Instance.Init();
// Read whether to set full screen from the configuration file
string s_isFullScreen = ConfigManager.Instance.GetShowConfig("isFullScreen");
bool b_isFullScreen = false;
if (bool.TryParse(s_isFullScreen, out b_isFullScreen))
{
if (b_isFullScreen)
HostWindowType = NetDimension.NanUI.HostWindow.HostWindowType.Kiosk;
else
HostWindowType = NetDimension.NanUI.HostWindow.HostWindowType.System;
}
}
}
}
3、 ... and 、 main interface
MainIndex Code , Notice the StartUrl Of URL And the code above URL Be consistent
using NetDimension.NanUI;
using NetDimension.NanUI.HostWindow;
using NetDimension.NanUI.JavaScript;
using System.Drawing;
using Utils;
namespace NanUIFramework
{
public class MainIndex : Formium, WebConsoleLog
{
public override HostWindowType WindowType => Program.HostWindowType;
public override string StartUrl => "Load.Resource.Html/index.html";
// Whether the interface is initialized
private bool WindowsIsReady = false;
#region Browser functions
protected override void OnReady()
{
// Display console
string isShow = ConfigManager.Instance.GetShowConfig("isShowConsole");
if (isShow.Equals("True")) ShowDevTools();
WindowsIsReady = true;
// register JS Method
MapClrObjectToJavaScript();
}
private void MainIndex_BeforeClose(object sender, NetDimension.NanUI.Browser.FormiumCloseEventArgs e)
{
Log.Print("[MainIndex] When the browser is closed ");
}
private void MainIndex_LoadEnd(object sender, NetDimension.NanUI.Browser.LoadEndEventArgs e)
{
Log.Print("[MainIndex] When the web page is loaded ");
InvokeIfRequired(async () =>
{
var result = await EvaluateJavaScriptAsync("js Methods ");
if (result.Success)
{
JavaScriptValue retval = result.ResultValue;
string type = retval.GetBool() ? "0" : "1";
string script = string.Format("console.log('{1}')", " Incoming value ");
ExecuteJavaScript(script);
}
});
}
#endregion
#region register JS Method
private void MapClrObjectToJavaScript()
{
var obj = JavaScriptValue.CreateObject();
// Example
obj.SetValue("JsCallCSharp", JavaScriptValue.CreateFunction(args =>
{
return null;
}));
RegisterExternalObjectValue("CSharpProject", obj);
}
#endregion
#region Show log in browser
/// <summary>
/// Console output log
/// </summary>
/// <param name="value"></param>
public void ShowConsoleLog(string value)
{
if (!WindowsIsReady) return;
string script = string.Format("console.log('[C# journal ]{0}')", value);
ExecuteJavaScript(script);
}
#endregion
#region Constructors
public MainIndex()
{
BeforeClose += MainIndex_BeforeClose;
LoadEnd += MainIndex_LoadEnd;
if (Program.HostWindowType == HostWindowType.System)
{
// The size of the interface
string s_width = ConfigManager.Instance.GetShowConfig("Width");
string s_heigth = ConfigManager.Instance.GetShowConfig("Height");
int width = 0;
int height = 0;
bool b_width = int.TryParse(s_width, out width);
bool b_height = int.TryParse(s_heigth, out height);
if (!b_width || !b_height)
Size = new Size(1280, 800);
else
Size = new Size(width, height);
StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
Title = " terminal ";
Icon = System.Drawing.Icon.ExtractAssociatedIcon("NanUIFramework.exe");
CanMaximize = false;// The maximize interface button... Is not allowed
Resizable = false;// Whether the form can change size
}
Mask.BackColor = Color.White;
}
#endregion
}
}
After completing the above steps , It's not enough ,View All the files in the folder ( In addition to folders ) Should be changed to embedded resources

NanUI 0.77 edition Open console
In the interface rewrite Method OnWindowReady in , call ShowDevTools The method can
protected override void OnWindowReady(IWebBrowserHandler browserClient)
{
// Display console
WebBrowser.ShowDevTools();
}NanUI 0.77 edition C# Call multiple parameter JS Method
NanUI edition :0.77
JS Code :
function TwoParameter(n1,n2) {
console.log("n1:" + n1);
console.log("n2:" + n2);
}C# Code :
WebBrowser.ExecuteJavascript("TwoParameter(2,4)");perform :

NanUI 0.77 edition Passing array parameters
NanUI edition :0.77
After inquiry NanUI The author of , Whether it's 0.77 still 0.88 edition , Can't go through ExecuteJavaScript("console.log('Hello NanUI')"); In this way, the array is passed , But you can use ExecuteJavaScript("console.log([1,2,3])"); Pass the array in this way , If you want to pass C# object , Can be C# Object to JSON, And then use JSON String transfer .
Case study 1:JS Pass an array and a callback to C#
JS Code :
function on_Click() {
var arr = new Array();
arr.push(" Croton ");
arr.push(40);
arr.push("2077/5/23");
// call C# And pass in an array , One JS The callback
try {
my.callbackTest(arr, sayByeBye);
} catch (e) {
console.log(" call C# callbackTest Method failed ");
}
}
// to C# Callback
function sayByeBye(obj) {
var str = " Parameters success:" + obj.success + " Parameters text:" + obj.text
console.log(str);
}C# Code :
// receive JS The callback , And pass your own parameters to
var callbackTestFunc = myObject.AddFunction("callbackTest");
callbackTestFunc.Execute += (func, args) =>
{
// Get array parameters
var myArr = args.Arguments.FirstOrDefault(p => p.IsArray);
if(myArr != null)
{
// Get the drug name
string drugName = myArr.GetValue(0).StringValue;
// Get quantity
int num = myArr.GetValue(1).IntValue;
// Get validity
string validity = myArr.GetValue(2).StringValue;
string ret = string.Format(" Drug name :{0}, Number :{1}, The period of validity :{2}",drugName,num,validity);
MessageBox.Show(ret);
}
// Get callback parameters
var callback = args.Arguments.FirstOrDefault(p => p.IsFunction);
if (callback != null)
{
// Create a Object Variable of type
var callbackArgs = CfrV8Value.CreateObject(new CfrV8Accessor());
// Add one Bool Type value :success
callbackArgs.SetValue("success", CfrV8Value.CreateBool(true), CfxV8PropertyAttribute.ReadOnly);
// Add one string Type value :text
callbackArgs.SetValue("text", CfrV8Value.CreateString(" I am a C# Parameters "), CfxV8PropertyAttribute.ReadOnly);
// use ExecuteFunction perform JS The callback passed , And set your own variables callbackArgs Pass to JS
callback.ExecuteFunction(null, new CfrV8Value[] { callbackArgs });
}
};function :
1. C# Get JS Array of :

2. C# Return to JS The object of

Case study 2:JS call C#, from C# Get an array
JS Code :
try {
var arr = my.TestCSharpToJSArr();
if (arr) {
console.log(" Parameters 1:" + arr[0]);
console.log(" Parameters 2:" + arr[1]);
}
} catch (e) {
console.error(" call TestCSharpToJSArr Method failed ");
}C# Code :
// Pass an array to JS
var TestCSharpToJSArr = myObject.AddFunction("TestCSharpToJSArr");
TestCSharpToJSArr.Execute += (func, args) =>
{
CfrV8Value arr = CfrV8Value.CreateArray(2);
arr.SetValue(0, CfrV8Value.CreateString(" eggplant "));
arr.SetValue(1, CfrV8Value.CreateString(" cucumber "));
args.SetReturnValue(arr);
};
function :
NanUI 0.77 edition Set the full screen display of the form ( similar Kiosk Pattern )
For the display console , And some configuration of forms , such as , Width and height , Whether to display parameters such as full screen , I wrote it all in one xml In the configuration file .
How to read xml The parameters of the file , I don't post code here , Du Niang has many posts .
stay Program.cs in , I defined HostWindowType A default value for , And read xml In file isFullScreen The value of the node , To set the display mode of the form
using NetDimension.NanUI;
using System;
using System.Windows.Forms;
using Utils;
namespace NanUI077_SourceCode
{
static class Program
{
public static MainIndex MainIndexs = null;
public static HostWindowType HostWindowType = HostWindowType.Standard;
/// <summary>
/// The main entry point for the application .
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Init();
Bootstrap
.Initialize()
.WithChromiumCommandLineArguments((procesName, cmd) =>
{
// Deal with... Here CEF Command line parameters of
})
.WithChromiumSettings(settings =>
{
// Deal with... Here CEF Set up
})
.WhenLibCefNotFound(args =>
{
// If NanUI The initiator did not detect the correct CEF as well as ChromiumFX Running environment , This process will be performed .
MessageBox.Show(" Not detected Chromium Embedded Running environment , Please make sure the libcef The environment is configured correctly .", "libcef.dll is not found", MessageBoxButtons.OK, MessageBoxIcon.Error);
})
.Run(() =>
{
MainIndexs = new MainIndex();
return MainIndexs;
});
}
private static void Init()
{
// Initialize configuration file
ConfigManager.Instance.Init();
// Read whether to set full screen from the configuration file
string s_isFullScreen = ConfigManager.Instance.GetShowConfig("isFullScreen");
if (string.IsNullOrEmpty(s_isFullScreen)) return;
bool b_isFullScreen = false;
if (bool.TryParse(s_isFullScreen, out b_isFullScreen))
{
if (b_isFullScreen)
HostWindowType = HostWindowType.UserCustom;
else
HostWindowType = HostWindowType.Standard;
}
}
}
}
stay mainIndex in OnStandardFormStyle In the method , take UserCustorm Just change the mode to full screen , The order of the main codes here , Borderless mode must be written in the first sentence , Otherwise you won't be able to full screen
// If you want to further customize your window style , Please reload OnStandardFormStyle Method ,
// And use style Parameter to set the window start position 、 size 、 Icon 、 Border style and other information .
protected override void OnStandardFormStyle(IStandardHostWindowStyle style)
{
base.OnStandardFormStyle(style);
Title = " first NanUI application ";
if (Program.HostWindowType == HostWindowType.Standard)
{
style.Width = 1280;
style.Height = 720;
style.Icon = System.Drawing.SystemIcons.WinLogo;
style.StartPosition = FormStartPosition.CenterScreen;
style.MaximizeBox = false;// Don't maximize
style.FormBorderStyle = FormBorderStyle.FixedSingle;// Do not drag the border to enlarge
}
else if(Program.HostWindowType == HostWindowType.UserCustom)
{
style.FormBorderStyle = FormBorderStyle.None;// Borderless mode
style.WindowState = FormWindowState.Maximized;// Maximization window
style.TopMost = true;// Set the topmost window ( Show at the front )
}
}
NanUI 0.77 edition Bootstrap class API
Here is Bootstrap Class :
Static members
CEF_VERSION type:const string Indicates the of the current frame Cef edition
CommandLineArgs type:string[] Command line arguments for the current process
Static attribute
ApplicationDataDirectory { get; } type:string
Get the data directory of the application , The application data directory is used to store NanUI Relevant data . Usually this directory is located in %appdata%Net Dimension Studio in .
CacheDirectory { get; } type:string
Get the application Chromium Cache directory for , The cache directory is used to store Chromium Zero time data , Contains browsing records 、Cookies data 、LocalStorage Data etc. . Typically, this directory is located in the application data directory .
CurrentContext { get; } type:Bootstrap example
Get current Bootstrap Singleton instance of . The return value is not available until the application initialization starts ; otherwise , return null.
DefaultBrowserSetting { get; } type:CfxBrowserSettings
Chromium Browser default settings , About browser settings CefBrowserSettings Relevant setting information and functions of , Please refer to this document .
LibCefDirPath { get; } type:string
obtain libcef.dll The path of . When NanUI Automatically search for Cef as well as ChromiumFX Binary dependencies of , This property has a return value ; Otherwise return to null, On behalf of NanUI Failed to find the correct dependency path , After starting the application, an exception will be thrown .
PlatformArchitecture { get; } type:enum[x86|x64]
Get the system architecture of the current application
ResourceDirPath { get; } type:string
obtain Cef Of Resources Catalog .Resources The catalog contains Chromium Necessary documents for operation , These documents are indispensable .NanUI Will be based on LibCefDirPath The value of automatically finds the directory and verifies the directory file , This property does not have a return value until it is verified ; Otherwise return to null, Similarly, an exception will be thrown after starting the application .
SubprocessPath { get; } type:string
return NanUI The path of the subprocess executable . If in Bootstrap Specified during initialization UseDefaultBrowserSubpress() characteristic , that NanUI Will automatically search for NanUI Subprocess executable , This property has a return value ; Otherwise return to null, After starting the application, an exception will be thrown .
Static methods
void Announce()
Print... In the console NanUI Information about . The information is in NanUI When the main process starts, it has automatically printed .
int ExecuteProcess()
Execute application subprocesses . If no child process is specified separately or no UseDefaultBrowserSubpress() characteristic , Then the application executes itself as Chromium Can be inherited by child processes. , Otherwise... Will be used Subprocess.exe As a child process .
Bootstrap Initialize()
notice NanUI Start initializing the runtime environment , And back to Bootstrap Class .
void Log(params ColorToken[] tokens);
Print the log in the console ,NanUI The console print module uses ColoredConsole Library to realize the coloring of console content , For information, please refer to ColoredConsole project .
void RegisterCustomResourceHandler(Func<CustomResource> resourceHandler);
Register custom resource processor . Use this method to register any CustomResource The derived class . The main principle of resource processor is to intercept Http request , When Url Hit the preset in the resource processor Url when , Returns the specified file or information .
void Text(string text)
Print unimportant information in the console . Usually this information is presented in white on a black background .
Example method
BeforeApplicaitonRun(Func<Bootstrap, bool> beforeRun);
Set up a handler before the main form loads , Parameter is passed into the current Bootstrap example , Return to one Boolean Type indicates whether to continue Run() Method .
DisableHighDpiSupported()
Ban Chromium Of HighDPI Support . By default ,NanUI To enable the Chromium Of HighDPI Support , If your application is not new Windows System ( for example Windows 7) Developed , Then you need to explicitly specify this feature to avoid Chromium Follow the system DPI The zoom .
RegisterChromiumExtension(string name, Func<ChromiumExtensionBase> register)
by Chromium Of Javascript Environment registration extension . Parameters name Is the unique name of the extension , Parameters register Yes, it specifies that the return value is ChromiumExtensionBase Proxy of type ,ChromiumExtensionBase Is the base class for any custom extension .
UseDefaultBrowserSubpress()
Specify the use of NanUI The default subprocess application . To use this feature , You need to install... For your application in advance NanUI Subprocess application .
WhenLibCefNotFound(Action<LibCefNotFoundArgs> action)
Set up NanUI Failed to automatically find libcef.dll Dependency is the handler of the . Parameters LibCefNotFoundArgs Contains several read-only properties :Architecture - Just the system architecture of the current application ;ApplicationStartupPath - The startup path of the application ;DataPath - The data path of the application . In this agent , You can implement your own path lookup logic , Or realize Cef Depending on the remote download of the project , Last , Put your customized Cef The dependency storage address is written back to LibCefDir Properties of the , The system will detect the path you specified again , If meet NanUI Operation requirements of , Then the application continues to initialize ; otherwise , An exception will be thrown .
WithApplicationDataDirectroty(string dataDir)
Set custom application data directory path .
WithCustomLibCefDirPath(string libCefDirPath)
Set up custom Cef Dependency storage directory path .
WithDebugModeEnabled()
Turn on debugging mode . By default NanUI Debugging mode is off , In non debugging mode NanUI Output of some unnecessary logs is disabled , Outside the edit menu item , Removed Chromium Other context menus .
WithChromiumCommandLineArguments(Action<string, CfxCommandLine> buildAction);
Customize Chromium Command line parameters of , The first parameter of the proxy method is processType, The second parameter is the shortcut setter of command line parameters . About Chromium Command line parameters of , Please refer to this document .
WithChromiumSettings(Action<CfxSettings> buildAction)
Customize Chromium Parameters of . The first parameter of the proxy method is Chromium Shortcut setter for settings . About Chromium Set relevant parameters , Please refer to this document .
void Run(Func<Formium|Form|ApplicationContext> runAction)
initialization NanUI And run the application main form . Executing this method means NanUI The initialization of the running environment is completed . You can only execute this method once , Executing this method multiple times will throw an exception .
end
边栏推荐
- Tips for unity transparent channel
- Image-Level 弱监督图像语义分割汇总简析
- Disease knowledge discovery based on spo semantic triples
- 我的创作纪念日-从心出发
- 中值滤波器
- 敏捷开发与DevOps的对比
- Redis data operation
- 31. Opinion-based Relational Pivoting forCross-domain Aspect Term Extraction 阅读笔记
- [ostep] 04 virtualized CPU - process scheduling strategy
- Mysql-04 storage engine and data type
猜你喜欢

Keyboard shortcut to operate the computer (I won't encounter it myself)

C# NanUI 相关功能整合

研发了 5 年的时序数据库,到底要解决什么问题?

Technology evolution analysis framework based on two-level topic model and its application

Low power multi-channel wfas1431 wireless data acquisition and transmission instrument operation process description
网络图片转本地导致内核退出

A survey of machine learning based technology term recognition

【整数规划】

Seata deployment and microservice integration

MySQL-03 数据库操作
随机推荐
『BaGet』带你一分钟搭建自己的私有NuGet服务器
敏捷开发与DevOps的对比
WPF 常用功能整合
Comparison between agile development and Devops
Redis data operation
Technology evolution analysis framework based on two-level topic model and its application
Detailed explanation of alter field of MySQL Foundation
Seata deployment and microservice integration
A survey of machine learning based technology term recognition
使用cpolar建立一个商业网站(申请网站安全证书)
【干货】MySQL索引背后的数据结构及算法原理
Mlx90640 infrared thermal imager temperature sensor module development notes (6)
Mysql-03 database operation
One stop monitoring of the software and hardware infrastructure of the whole university, and Suzhou University replaces PostgreSQL with time series database
【文件上传漏洞-06】分布式配置文件攻击实验—以upload-labs-4为例
Basic syntax of MySQL DDL and DML and DQL
winscp传输文件和VNC连接问题
Instructions for various interfaces of hand-held vibrating wire collector vh03
当AI邂逅生命健康,华为云为他们搭建三座桥
[dry goods] data structure and algorithm principle behind MySQL index