Harmony gives you an elegant(优雅的) and high level way to alter functionality(实用地更改) in applications written in C#. It does this at runtime by monkey patching methods unlike other solutions that change the content of dll files.
It supports Mono and .NET environments on Windows, Unix and macOS except when Unity uses the stripped down NetStandard profile (.NET 4.x profile works fine). Harmony is used in mainstream Unity games and many other applications.(不仅仅用于 Unity 游戏,还有其他的应用程序)
Designed to be used by multiple users (usually called Mods) that would otherwise override each others hooks, it was originally created for the game RimWorld and its large modding community by Andreas Pardeike.
Enjoy!
/Andreas Pardeike
......
Introduction
Harmony - a library for patching, replacing and decorating .NET methods during runtime.
Harmony does not provide you with a way to run your own code within an application that is not designed to execute foreign code. You need a way to inject at least the few lines that start the Harmony patching and this is usually done with a loader. Here are some common examples of loaders (incomplete):
To add Harmony manually to your Visual Studio project, you right-click on References in your solution explorer and choose Manage NuGet Packages, then search for "Harmony Library" and install it.
Import
Once you reference Harmony correctly, you should be able to import it by adding Harmony to your imports. That gives you code completion so you can discover the API:
using HarmonyLib;
Creating a Harmony instance
Most patch operations require a Harmony instance. To instantiate Harmony, you simply call
var harmony = new Harmony("com.company.project.product");
The id should be in reverse domain notation and must be unique. In order to understand and react on existing patches of others, all patches in Harmony are bound to that id. This allows other authors to execute their patches before or after a specific patch by referring to this id.
Patching using annotations
If you prefer annotations to organize your patches, you instruct Harmony to search for them by using PatchAll():
var assembly = Assembly.GetExecutingAssembly();harmony.PatchAll(assembly);// or implying current assembly:harmony.PatchAll();
which will search the given assembly for all classes that are decorated with Harmony annotations. All patches are registered automatically and Harmony will do the rest.
using System;using System.Windows.Froms; // 我们可以用 MessageBox 来看看有没有成功载入using HarmonyLib;namespace MyPatch { public static class EndPoint { public static void Start() { var harmony = new Harmony("my.patch"); harmony.PatchAll(); MessageBox.Show("成功注入!"); } }}